Microsoft ASP.NET Ajax Drag and Drop Tutorial



Beta 2 Source Code

RC Source Code (Web Project)

July 2007 Futures CTP (Web Project)


2007 Update


The linked zip files above have been updated for the July 2007 CTP of AJAX Futures. The only breaking change worth noting between the AJAX Futures beta and later CTPs is that the syntax for ScriptReferences in the ScriptManager and ScriptManagerProxy has changed.

Whereas in the beta, you would have written:

     <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Scripts>
            <asp:ScriptReference Assembly="Microsoft.Web.Preview" Name="Microsoft.Web.Resources.ScriptLibrary.PreviewScript.js" />   
            <asp:ScriptReference Assembly="Microsoft.Web.Preview" Name="Microsoft.Web.Resources.ScriptLibrary.PreviewDragDrop.js" />   
        </Scripts>
     </asp:ScriptManager>

you now should use the shortened form:

     <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Scripts>
            <asp:ScriptReference Assembly="Microsoft.Web.Preview" Name="PreviewScript.js" />   
            <asp:ScriptReference Assembly="Microsoft.Web.Preview" Name="PreviewDragDrop.js" />   
        </Scripts>
     </asp:ScriptManager>

Preface


The hardworking Atlas/Ajax team has greatly improved the architecture of the Ajax Extensions framework with the Beta 2, making it much more rational and easy to use for future adopters. Sadly, for us early adopters, this also meant a large number of breaking changes and a bit of a struggle trying to figure out the new paradigms for programming ASP.NET.  At this point in time, the documentation hasn’t yet caught up with the innovation, and so the best place to look for reliable information about how to use ASP.Net is to go the professional blogs of the various Microsoft developers: Bertrand LeRoy, Eilon Lipton, Scott Guthrie.  The blog of Miljan Braticevic of Component Art was also extremely helpful.  Greatest thanks to mavenger00 at www.codeproject.com, who got me over a major pain point and found an error in the official xml script documentation that no one else seems to have.  While the upgrade of this tutorial was a little painful, it was also instructive.  The only thing I think I don’t like about the new Beta 2 is the rebranding of Atlas — “Atlas” was a much more convenient moniker, and at this point I’m not totally sure when or how to use the terms ASP.NET Ajax, Ajax Extensions, Ajax Futures, etc.  I do my best to scatter them about randomly and interchangeably to give a false sense of authoritativeness.

Introduction


This tutorial is intended to help readers understand how certain aspects of Microsoft’s new Ajax Extensions technology works. Ajax Extensions is intended to simplify the development of Ajax-style functionality.  As with all technology, however, to use a tool well, it is important to understand the underlying technology that Atlas abstracts.  One of the key ASP.NET Ajax abstractions is the new XML markup syntax developed to make coding with Ajax easier (originally included with the core Atlas files, XML markup is now a part of the CTP called Ajax Futures).  With XML markup, developers can modify their code declaratively.  However, there are times when a developer may want to be able to change her code programmatically, and in order to accomplish this, she will need to understand that underneath the markup abstraction, she is actually dealing with good ‘ol javascript and some custom javascript libraries developed by Microsoft.  In order to demonstrate the relationship between the Atlas declarative model and the programmatic model, I will go through a series of examples in which the same task will be accomplished both declaratively and programmatically.  I will be demonstrating how to use the PreviewDragDrop library file to perform basic drag-drop operations as well as setting up drop zones. 


Background


As I write this, Microsoft has made some important changes to ASP.NET Ajax for the Beta 2 that have the unfortunate side-effect of breaking most of the original Atlas implementation, and has required a bit of rework of the original samples.  These revised examples apply to the Beta 2 of ASP.NET Ajax. Future releases of Ajax Extensions may affect the accuracy of this tutorial.  I will attempt to update the code as new versions of Ajax Extensions become available.  Ajax Extensions works with .Net 2.0 and will work with Orcas when it is released.

The Topsy-Turvy World: Witches and Spies


In Part II, Question 2 of the Malleus Maleficarum (The Hammer of the Witches), the 15th century witch hunter’s manual, the authors ask:



Is it lawful to remove witchcraft by means of further witchcraft, or by any other forbidden means?


 This is a variation on the question concerning means and ends, but with a poetic twist.  In the standard form of the question, we evaluate the two terms and try to determine if the good we seek to accomplish is greater than, or less than, the evil that is required to accomplish it, and if the answer is yes, then we call these means a necessary evil.  In the form posed by the Malleus Maleficarum, there is a more direct relationship between the means to be used and the evil to be overcome.  They are neither greater nor less than, but are in fact identical to the evil to be overcome.


In metaphysical jurisprudence, Dante calls this relationship between the crime and the punishment  contrapasso, or the counter-suffering that a soul suffers for the sins he committed in life.  Through this principle, people in sinning choose their own meet punishment in the afterlife, and the cosmic order is maintained.  Thus, Paolo and Francesca, who were caught up in each other’s lust in life, are caught up in in an eternal whirlwind in the afterlife, and the epicureans, who insist that the soul is permanently tied to the body, are forced to drag their bodies around in hell.


This poetic principle which assures justice with regard to punishment, because it makes the punishment always fit the crime, has a jarring effect when applied to practical reasoning and police work, which occur before any punishment is necessary.  By using the means of the enemy we seek to overcome, we somehow perpetuate the evil that we seek to destroy.  Cosmically, this evil is somehow transferred to us.  It is a standard trope of science fiction that when we use the tools of our enemy, we become no better than our enemy. 


There is a direct relationship between the witch-hunting of the 15th century, and the cold war of the 20th.  Not only were we similarly caught in a general fear about an enemy that we were not certain we could overcome, but the same temptations about the tools to be used were raised by the nature of the conflict.  Deviousness and ruthlessness, an absence of morality, are the greatest strengths of the enemy.  To what extent must we suspend our own morality in order to defeat this enemy?  And having done so, to what extent are we still the good guys.


In the 15th century, the advice to witch-hunters was to not use the tools of the witches.  In the Malleus Maleficarum, this is stated as an absolute prohibition, with the explanation that any attempt to use magic will either directly call upon the aid of demons, or will open the practitioner of such means up to the influence of the demons.


In the 20th century, we were more accommodating toward the Devil.  In The Spy Who Came In From The Cold, John Le Carre places the following words in the mouth of Control, the head of the Britain’s Secret Service, who is explaining to the hero, Alec Leamas, why he must go on just one more mission:


 



“Thus we do disagreeable things, but we are defensive.  That, I think, is still fair.  We do disagreeable things so that ordinary people here and elsewhere can sleep safely in their beds at night.  Is that too romantic?  Of course, we occasionally do very wicked things”; he grinned like a schoolboy.  “And in weighing up the moralities, we rather go in for dishonest comparisons; after all, you can’t compare the ideals of one side with the methods of the other, can you, now?”


Leamas was lost.  He’d heard the man talked a lot of drivel before getting the knife in, but he’d never heard anything like this before.


“I mean you’ve got to compare method with method, and ideal with ideal.  I would say that since the war, our methods — ours and those of the opposition — have become much the same.  I mean you can’t be less ruthless than the opposition simply because your government’s policy is benevolent, can you now?”  He laughed quietly to himself: “That would never do,” he said.


 


 But if our actions are justified because we are the good guys, at what point are we no longer able to distinguish ourselves from the bad guys and suddenly find ourselves in Hegel’s verkehrte Welt, the inverted world in which we are no longer ourselves?  This is a question that is raised with great regularity in modern politics, in world affairs, and in our daily lives.  The problems of the topsy-turvy world arise when we begin to practice a negative ethics rather than a positive one, in which we are defined much more by what we are not, rather than by what we are.

Technological Similes (e.g., Ajax is like…)


 As mentioned in a previous post, programmers typically explain one technology by referencing another more familiar technology.  What sometimes happens, however, is that the technology that was thought to be more familiar, and consequently believed to have explanatory power, in fact was simply originally explained by referencing some third vaguely understood technology; but time made the simile comfortable and vanity made it acceptable.  We only become aware of the semantic web we programmers weave when we are finally forced to use one of the referenced technologies and discover, once again, what a strange and incomprehensible thing programming is.  The experience is a bit like the shock felt by the woman who brought home a stray dog from Paris only to discover that it was really a large tailless rat.


To find out what one of the trendier new technologies is really like, I recently consulted Google.  A google search on “Ajax is like…” turns up the following results:



“Comparing Java and AJAX is like comparing apples and blue.”


“[U]sing Ajax is like consuming alcohol in public.”


“[A]jax is like instant messaging….”


“Customers asking for AJAX is like a prospective homeowner walking over to the contractors hired to do the building and handing them a saw.”


“AJAX is like Flash or HTML.”


“AJAX is like a javascript.”


“AJAX is like Javascript on steroids.”


“AJAX is like web services.”


“[A]jax is like everything else on line, it will be abused by various low lifes.”


“Ajax is like to partial update in Intraweb I am wrong?”


“Ajax is like ‘roller skates for the web.'”


“Ajax is like shell, Perl, Ruby. Ajax is like UNIX.”


“AJAX is like a Hooker turn School Teacher, it has a dirty secret and unless you get it alone and play with it, you won’t pickup on it’s secrets until it’s too late.”


“Ajax is, like stated in the essay, a new way to think about user interfaces on the web….”


“AJAX is like wearing 70’s djeans with an Hugo Boss Shoes….”


“AJAX is like Dinosaur cloning in Jurassic park.”


“AJAX is like folding a web page origami-style into a Lego brick….”


“AJAX is like a house of cards, and when a browser vendor screws up on a revision it’ll all come tumbling down.”


“AJAX is like putting a tiny bandage on a gaping wound the size of a grapefruit.”


“Ajax is like DHTML was 4 years ago, like javascript was 6 years ago, like applets were 8 years ago.”


“AJAX is like the killer buzzword.”


IE7 CSS Rendering Problem for DasBlog Project84 Theme

This site uses DasBlog as it’s blogging engine.  One of the themes that comes with DasBlog, Project84, has a rendering problem in IE7 that causes the footer to bleed into the main page somewhere a few inches from the top, when it should, of course, display at the bottom of the page.


The problem turns out to be only one line in the style.css file:



html, body{height:100%;}

Comment this out and the page should render correctly.  This also affects the Project84Green theme.


I viewed the corrected style in Firefox 1.5, IE6 and IE7 and did not note any issues. 

Methodology and Methodism


This is simply a side by side pastiche of the history of Extreme Programming and the history of Methodism.  It is less a commentary or argument than simply an experiment to see if I can format this correctly in HTML.  The history of XP is drawn from Wikipedia.  The history of Methodism is drawn from John Wesley’s A Short History of Methodism.


 








Software development in the 1990s was shaped by two major influences: internally, object-oriented programming replaced procedural programming as the programming paradigm favored by some in the industry; externally, the rise of the Internet and the dot-com boom emphasized speed-to-market and company-growth as competitive business factors. Rapidly-changing requirements demanded shorter product life-cycles, and were often incompatible with traditional methods of software development.


The Chrysler Comprehensive Compensation project was started in order to determine the best way to use object technologies, using the payroll systems at Chrysler as the object of research, with Smalltalk as the language and GemStone as the persistence layer. They brought in Kent Beck, a prominent Smalltalk practitioner, to do performance tuning on the system, but his role expanded as he noted several issues they were having with their development process. He took this opportunity to propose and implement some changes in their practices based on his work with his frequent collaborator, Ward Cunningham.


The first time I was asked to lead a team, I asked them to do a little bit of the things I thought were sensible, like testing and reviews. The second time there was a lot more on the line. I thought, “Damn the torpedoes, at least this will make a good article,” [and] asked the team to crank up all the knobs to 10 on the things I thought were essential and leave out everything else. —Kent Beck


Beck invited Ron Jeffries to the project to help develop and refine these methods. Jeffries thereafter acted as a kind of coach to instill the practices as habits in the C3 team. Information about the principles and practices behind XP was disseminated to the wider world through discussions on the original Wiki, Cunningham’s WikiWikiWeb. Various contributors discussed and expanded upon the ideas, and some spin-off methodologies resulted (see agile software development). Also, XP concepts have been explained, for several years, using a hyper-text system map on the XP website at “www.extremeprogramming.org” circa 1999.


Beck edited a series of books on XP, beginning with his own Extreme Programming Explained (1999, ISBN 0-201-61641-6), spreading his ideas to a much larger, yet very receptive, audience. Authors in the series went through various aspects attending XP and its practices, even a book critical of the practices. Current state XP created quite a buzz in the late 1990s and early 2000s, seeing adoption in a number of environments radically different from its origins.


Extreme Programming Explained describes Extreme Programming as being:



  • An attempt to reconcile humanity and productivity
  • A mechanism for social change
  • A path to improvement
  • A style of development
  • A software development discipline

The advocates of XP argue that the only truly important product of the system development process is code (a concept to which they give a somewhat broader definition than might be given by others). Without code you have nothing.

Coding can also help to communicate thoughts about programming problems. A programmer dealing with a complex programming problem and finding it hard to explain the solution to fellow programmers might code it and use the code to demonstrate what he or she means. Code, say the exponents of this position, is always clear and concise and cannot be interpreted in more than one way. Other programmers can give feedback on this code by also coding their thoughts.

 The high discipline required by the original practices often went by the wayside, causing certain practices to be deprecated or left undone on individual sites.


Agile development practices have not stood still, and XP is still evolving, assimilating more lessons from experiences in the field. In the second edition of Extreme Programming Explained, Beck added more values and practices and differentiated between primary and corollary practices.


In November, 1729, four young gentlemen of Oxford — Mr. John Wesley, Fellow of Lincoln College; Mr. Charles Wesley, Student of Christ Church; Mr. Morgan, Commoner of Christ Church; and Mr. Kirkham, of Merton College — began to spend some evenings in a week together, in reading, chiefly, the Greek Testament. The next year two or three of Mr. John Wesley’s pupils desired the liberty of meeting with them; and afterwards one of Mr. Charles Wesley’s pupils. It was in 1732, that Mr. Ingham, of Queen’s College, and Mr. Broughton, of Exeter, were added to their number. To these, in April, was joined Mr. Clayton, of Brazen-nose, with two or three of his pupils. About the same time Mr. James Hervey was permitted to meet with them; and in 1735, Mr. Whitefield.


The exact regularity of their lives, as well as studies, occasioned a young gentleman of Christ Church to say, “Here is a new set of Methodists sprung up;” alluding to some ancient Physicians who were so called. The name was new and quaint; so it took immediately, and the Methodists were known all over the University.


They were all zealous members of the Church of England; not only tenacious of all her doctrines, so far as they knew them, but of all her discipline, to the minutest circumstance. They were likewise zealous observers of all the University Statutes, and that for conscience’ sake. But they observed neither these nor anything else any further than they conceived it was bound upon them by their one book, the Bible; it being their one desire and design to be downright Bible-Christians; taking the Bible, as interpreted by the primitive Church and our own, for their whole and sole rule.


The one charge then advanced against them was, that they were “righteous overmuch;” that they were abundantly too scrupulous, and too strict, carrying things to great extremes: In particular, that they laid too much stress upon the Rubrics and Canons of the Church; that they insisted too much on observing the Statutes of the University; and that they took the Scriptures in too strict and literal a sense; so that if they were right, few indeed would be saved.


In October, 1735, Mr. John and Charles Wesley, and Mr. Ingham, left England, with a design to go and preach to the Indians in Georgia: But the rest of the gentlemen continued to meet, till one and another was ordained and left the University. By which means, in about two years’ time, scarce any of them were left.


In February, 1738, Mr. Whitefield went over to Georgia with a design to assist Mr. John Wesley; but Mr. Wesley just then returned to England. Soon after he had a meeting with Messrs, Ingham, Stonehouse, Hall, Hutchings, Kinchin, and a few other Clergymen, who all appeared to be of one heart, as well as of one judgment, resolved to be Bible-Christians at all events; and, wherever they were, to preach with all their might plain, old, Bible Christianity.


They were hitherto perfectly regular in all things, and zealously attached to the Church of England. Meantime, they began to be convinced, that “by grace we are saved through faith;” that justification by faith was the doctrine of the Church, as well as of the Bible. As soon as they believed, they spake; salvation by faith being now their standing topic. Indeed this implied three things: (1) That men are all, by nature, “dead in sin,” and, consequently, “children of wrath.” (2) That they are “justified by faith alone.” (3) That faith produces inward and outward holiness: And these points they insisted on day and night. In a short time they became popular Preachers. The congregations were large wherever they preached. The former name was then revived; and all these gentlemen, with their followers, were entitled Methodists.


In March, 1741, Mr. Whitefield, being returned to England, entirely separated from Mr. Wesley and his friends, because he did not hold the decrees. Here was the first breach, which warm men persuaded Mr. Whitefield to make merely for a difference of opinion. Those, indeed, who believed universal redemption had no desire at all to separate; but those who held particular redemption would not hear of any accommodation, being determined to have no fellowship with men that “were in so dangerous errors.” So there were now two sorts of Methodists, so called; those for particular, and those for general, redemption.

Methodology and its Discontents


A difficult aspect of software programming is that it is always changing.  This is no doubt true in other fields, also, but there is no tenure system in software development.  Whereas in academe, it is quite plausible to reach a certain point in your discipline and then kick the ladder out behind you, as Richard Rorty was at one point accused of doing, this isn’t so in technology.  In technology, it is the young who set the pace, and the old who must keep up.


The rapid changes in technology, with which the weary developer must constantly attempt to stay current, can be broken down into two types: there are advances in tools and advances in methodologies.  While there is always a certain amount of fashion determining which tools get used — for instance which is the better language, VB.Net or C#? –, for the most part development tools are judged based upon their effectiveness. This is not necessarily true concerning the methodologies of software development.  Which is odd since one would suppose that the whole point of a method is that it is a way of guaranteeing certain results — use method A, and B (fame, fortune, happiness) will follow.


There is even something of a backlash against methodism (or, more specifically, certain kinds of methodism) being led, interestingly enough, by tool builders.  For instance, Rocky Lhotka, the creator of the CSLA framework says:



I am a strong believer in responsibility-driven, behavioral, CRC OO design – and that is very compatible with the concepts of Agile. So how can I believe so firmly in organic OO design, and yet find Agile/XP/SCRUM to be so…wrong…?


I think it is because the idea of taking a set of practices developed by very high-functioning people, and cramming them into a Methodology (notice the capital M!), virtually guarantees mediocrity. That, and some of the Agile practices really are just plain silly in many contexts.


Joel Spolsky, the early Microsoft Excel Product Manager and software entrepreneur, has also entered the fray a few times.  Most recently, an blog post by Steve Yegge (a developer at Google) set the technology community on fire:



Up until maybe a year ago, I had a pretty one-dimensional view of so-called “Agile” programming, namely that it’s an idiotic fad-diet of a marketing scam making the rounds as yet another technological virus implanting itself in naive programmers who’ve never read “No Silver Bullet”, the kinds of programmers who buy extended warranties and self-help books and believe their bosses genuinely care about them as people, the kinds of programmers who attend conferences to make friends and who don’t know how to avoid eye contact with leaflet-waving fanatics in airports and who believe writing shit on index cards will suddenly make software development easier.
You know. Chumps.


The general tenor of these skeptical treatments is that Extreme Programming (and its umbrella methodology, Agile) is at best a put-on, and at worst a bit of a cult.  What is lacking in these analyses, however, is an explication of why programming methodologies like Extreme Programming are so appealing.  Software development is a complex endeavor, and its practitioners are always left with a sense that they are being left behind.  Each tool that comes along in order to make development easier always ends up making it actually more difficult and error prone (though also more powerful).  The general trend of software devlopment has consistently been not less complexity, but greater complexity.  This leads to an indemic sense of insecurity among developers, as well as a sense that standing still is tantamount to falling behind.  Developers are, of course, generally well compensated for this burden (unlike, for instance, untenured academics who suffer from the same constraints) so there is no sense in feeling sorry for them, but it should be clear, given this, why there is so much appeal in the notion that there is a secret method which, if they follow it correctly, will grant them admission into the kingdom and relieve them of their anxieties and doubts.


One of the strangest aspects of these methodologies is the notion that methods need evangelists, yet this is what proponents of these concepts self-consciously call themselves.  There are Extreme Programming evangelists, SCRUM evangelists, Rational evangelists, and so on who write books and tour the country giving multimedia presentations, for a price, about why you should be using their methodology and how it will transform you and your software projects. 


So are software methodologies the secular equivalent of evangelical revival meetings?  It would depend, I suppose, on whether the purpose of these methodologies is to make money or to save souls.  Let us hope it is the former, and that lots of people are simply making lots of money by advocating the use of these methodologies.

Metaphors and Software Development

“But the greatest thing by far is to have a mastery of metaphor. This alone cannot be imparted by another; it is the mark of genius, for to make good metaphors implies an eye for resemblances.”  — Aristotle, The Poetics

 



It is a trivial observation that software programmers use a lot of metaphors.  All professions are obliged to invoke metaphors in one way or another, but in software programming I think the program is so extensive that we are not even aware of the fact that creating metaphors is our primary job.  We are only ever immediately aware of the metaphorical character of our profession when we use similes to explain technical matters to our managers.  Such-and-such technology will improve our revenue stream because it is like a new and more reliable conduit for information. It can be combined with sundry-and-other technology, which acts as a locked box for this information.


When speaking with technical colleagues, in turn, we use a different set of metaphors when explaining unfamiliar technology.  We say that “Ajax is like Flash”, “Flash is like instant messaging”, “instant messaging is like talking to services in a SOA”, “SOA is like mainframe programming”, b is like c, c is like d, d is like e, and so on.  Every technology is explained in reference to another technology, which in turn is just a metaphor for something else.  But does explicating one metaphor by simply referencing another metaphor really explain anything?  Is there a final link in the chain that ultimately cascades meaning back up the referential chain?


I have occasionally seen these referential chains referred to as a prison house of language, though perhaps a house of mirrors would be more appropriate in this case.  We work with very complex concepts, and the only way to communicate them is through metaphors, even when, as in a fun house, the only points of reference we have for explaining these concepts are other concepts we find reflected in a reflection of a reflection.  This metaphorical character of our occupation, however, is typically hidden from us because we use a different set of terms to describe what we do.  We don’t typically speak about metaphors in our programming talk; instead we speak of abstractions.


Not only are abstractions explained in terms of other abstractions, but they are also typically abstractions for other abstractions.  In Joel Spolsky’s explication of “Leaky Abstractions” (which is, yes, also a metaphor) we discover that TCP is really an abstraction thrown over IP.  But IP is itself an abstraction of other technologies, which in turn may in themselves also involve further abstractions.  At what point do the abstractions actually end?  Is it when we get to the assembler language level?  Is it when we get to machine language?  Do we finally hit bottom when we reach the point of talking about electricity and circuit boards?


Again, I will posit (in a handwaving and unsubstantiated manner) that the main occupation of a software programmer is working with metaphors.  Taking this as a starting point, it is strange that in the many articles and discussion threads addressing the question, what makes a good programmer?, poetry is never brought up. Overlooking Aristotle’s professed opinion that a gift for metaphor is something that cannot be taught, we might assume that if it is indeed something that can be cultivated, a likely starting point is through the reading and writing of poetry.  It would be a pleasant change if in looking over technical resumes, we also starting looking for signs that prospective employees to BigTech.com also were published in poetry journals or participated in local poetry readings.


But perhaps that is asking for too much.  The only other profession in which metaphors are applied extensively is in politics.  Just as metaphors are called abstractions in programming, in politics they are called “framing”.  Behind the notion of framing in politics is the assumption that certain metaphors are simply more naturally appealing than others.  The proper metaphor will motivate one’s audiences emotions either toward one’s platform or against one’s opponents platform.  The mastery of metaphor in politics, consequently, entails being able to associate one’s own position with the most emotively powerful metaphor into which one can fit one’s position. 


One interesting aspect of the endeavor of framing is that a political metaphor is required to be fitting, that is the metaphor one uses to explain a given position or argument must be appropriate to that argument, and an absence of fitting will generally detract from the force of the metaphor.  That there is this question of fittingness provides two ways to characterize political metaphors.  There are metaphors that seem to naturally apply to a given circumstance, and hence garner for the person who comes up with such metaphors a reputation for vision and articulateness.  Then there are metaphors that are so powerful that it does not matter so much that the circumstance to which it is applied is not so fitting, in which case the person who comes up with such metaphors gains a reputation as a scheming framer.


Determining which is which, of course, generally depends on where one is standing, and in either case we can say that both are masters of metaphor in Aristotle’s sense.  However, because there is so much question about the integrity of metaphors in politics, it is tempting to eschew the whole thing.  As wonderful as metaphors are, politics tends to make everything dirty in the end.


Which leaves software programming as the only place where metaphors can be studied and applied in a disinterested manner.  In programming, the main purpose of our abstractions is not to move people’s emotions, but rather to clarify concepts, spread comprehension and make things work better.  It is the natural home not only for mathematicians, but for poets.

V. Imperative Dropzones


 


To create dropzones using JavaScript instead of declarative script, just add the following JavaScript function to initialize your dropzone element with the custom dropzone behavior:


function addDropZoneBehavior(ctrl){
var dropZone = new Sys.UI.Control(ctrl);
var dropZoneBehavior = new Custom.UI.DropZoneBehavior();
dropZone.get_behaviors().add(dropZoneBehavior);
dropZoneBehavior.initialize();
}

To finish hooking everything up, call this addDropZoneBehavior function from the Atlas pageLoad() method, as you did in earlier examples for the addFloatingBehavior function. This will attach the proper behaviors to their respective HTML elements and replicate the drag and dropzone functionality you created above using declarative markup. If you want to make this work dynamically, just add the createDraggableDiv() function you already wrote for the previous dynamic example. As a point of reference, here is the complete code for creating programmatic dropzones:


<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1″ runat=”server”>
<title>Imperative Drop Targets</title>
<script type=”text/javascript”>
function addFloatingBehavior(ctrl, ctrlHandle){
var floatingBehavior = new Sys.UI.FloatingBehavior();
floatingBehavior.set_handle(ctrlHandle);
var dragItem = new Sys.UI.Control(ctrl);
dragItem.get_behaviors().add(floatingBehavior);
floatingBehavior.initialize();
}
function addDropZoneBehavior(ctrl){
var dropZone = new Sys.UI.Control(ctrl);
var dropZoneBehavior = new Custom.UI.DropZoneBehavior();
dropZone.get_behaviors().add(dropZoneBehavior);
dropZoneBehavior.initialize();
}
 
function pageLoad(){
addDropZoneBehavior($(‘dropZone’));
addFloatingBehavior($(‘draggableDiv’),$(‘handleBar’));
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<atlas:ScriptManager ID=”ScriptManager1″ runat=”server”>
<Scripts>
<atlas:ScriptReference ScriptName=”AtlasUIDragDrop” />
<atlas:ScriptReference Path=”scriptLibrary/DropZoneBehavior.js” />
</Scripts>
</atlas:ScriptManager>
<h2>Imperative Drop Targets with javacript</h2>
<div style=”background-color:Red;height:200px;width:200px;”>
<div id=”draggableDiv”
style=”height:100px;width:100px;background-color:Blue;”>
<div id=”handleBar”
style=”height:20px;width:auto;background-color:Green;”>
</div>
</div>
</div>
<div id=”dropZone” style=”background-color:cornflowerblue;
height:200px;width:200px;”>Drop Zone</div>
</form>
</body>
</html>
 

Conclusion


Besides the dropzone behavior, you may want to also write your own floating behavior. For instance, by default, elements decorated with the floating behavior simply stay where you drop them. You may want to extend this so that your floating div will snap back to its original location when you drop it outside of a drop zone. Additionally, you may want to change the way the dragged element looks while you are dragging it, either by making it transparent, changing its color, or replacing the drag image altogether. All this can be accomplished by creating a behavior that implements the IDragSource interface in the same way you created a custom class that implements the IDropTarget interface.


This tutorial should provide you with a starting point for extending the basic drag drop functionality provided with Atlas, to create your own behaviors and provide your own functionality. The next step is to build on this to create controls. Using this tutorial as a starting point, you can go on to create Atlas extender controls that implement your behaviors using declarative markup, or even turn around and create server-side controls that automatically create HTML elements with Atlas behaviors, with the choice being, once again, one between creating server-side controls that are either declarative, and consequently static, or imperative, and consequently slightly more complex but also more flexible. This is a topic that is much too large for the current tutorial; however, I hope that in the near future, someone will try to do for server-side Atlas programming what this tutorial attempts to do for client-side Atlas scripting.

IV. Declarative Dropzones


 


Being able to drag HTML elements around a page and have them stay where you leave them is visually interesting. To make this behavior truly useful, though, an event should be thrown when the drop occurs. Furthermore, the event that is thrown should depend on where the drop occurs. In other words, there needs to be behavior that can be added to a given HTML element that will turn it into a “dropzone” or a “drop target”, the same way that the floating behavior can be added to an HTML div tag to turn it into a drag and drop element.


In the following examples, I will show how Atlas supports the concept of dropzones. In its current state, Atlas does not support an out-of-the-box behavior for creating dropzone elements in quite the same way it does for floating elements. It does, however, implement behaviors for a DragDropList element and a DraggableListItem element which, when used together, allow you to create lists that can be reordered by dragging and dropping. If you would like to explore this functionality some more, there are several good examples of using the DragDropList behavior on the web, for instance, Introduction to Drag And Drop with Atlas.


The main disadvantage of the dragdropzone behavior is that it only works with items that have been decorated with the DragDropList behavior. The functionality that this puts at your disposal is fairly specific. To get the sort of open-ended dropzone functionality I described above, that will also work with the predefined floating behavior, you will need to write your own dropzone behavior class in JavaScript. Fortunately, this is not all that hard.


Atlas adds several OOP extensions to JavaScript in order to make it more powerful, extensions such as namespaces, abstract classes, and interfaces. You will take advantage of these in coding up your own dropzone behavior. If you peer behind the curtain and look at the source code in the AtlasUIDragDrop.js file, (you can do this with the Visual Studio debugger), you will find several interfaces defined there, including one for Sys.UI.DragSource and one for Sys.UI.DropTarget. In fact, both the FloatingBehavior class and the DraggableListItem class implement the Sys.UI.DragSource interface, while Sys.UI.DropTarget is implemented by the DragDropList class. The code for these two interfaces looks like this:


Sys.UI.IDragSource = function() {
this.get_dataType = Function.abstractMethod;
this.get_data = Function.abstractMethod;
this.get_dragMode = Function.abstractMethod;
this.onDragStart = Function.abstractMethod;
this.onDrag = Function.abstractMethod;
this.onDragEnd = Function.abstractMethod;
}
Sys.UI.IDragSource.registerInterface(‘Sys.UI.IDragSource’);
Sys.UI.IDropTarget = function() {
this.get_dropTargetElement = Function.abstractMethod;
this.canDrop = Function.abstractMethod;
this.drop = Function.abstractMethod;
this.onDragEnterTarget = Function.abstractMethod;
this.onDragLeaveTarget = Function.abstractMethod;
this.onDragInTarget = Function.abstractMethod;
}
Sys.UI.IDropTarget.registerInterface(‘Sys.UI.IDropTarget’);

Why do you need to implement these interfaces instead of simply writing out brand new classes to support drag, drop, and dropzones? The secret is that, behind the scenes, a third class, called the DragDropManager, is actually coordinating the interactions between the draggable elements and the dropzone elements, and it only knows how to work with classes that implement the IDragSource or the IDropTarget. The DragDropManager class registers which dropzones are legitimate targets for each draggable element, handles the MouseOver events to determine when a dropzone has a draggable element over it, and a hundred other things you do not want to do yourself. In fact, it does it so well that the dropzone behavior you are about to write is pretty minimal. First, create a new JavaScript file called DropZoneBehavior.js. I placed my JavaScript file under a subdirectory called scriptLibrary, but this is not necessary in order to make the dropzone behavior work. Next, copy the following code into your file:


Type.registerNamespace(‘Custom.UI’);

Custom.UI.DropZoneBehavior = function() {

Custom.UI.DropZoneBehavior.initializeBase(this);
this.initialize = function() {
Custom.UI.DropZoneBehavior.callBaseMethod(this, ‘initialize’);
// Register ourselves as a drop target.
Sys.UI.DragDropManager.registerDropTarget(this);
}
this.dispose = function() {
Custom.UI.DropZoneBehavior.callBaseMethod(this, ‘dispose’);
}
this.getDescriptor = function() {
var td = Custom.UI.DropZoneBehavior.callBaseMethod(this, ‘getDescriptor’);
return td;
}

// IDropTarget members.
this.get_dropTargetElement = function() {
return this.control.element;
}
this.drop = function(dragMode, type, data) {
alert(‘dropped’);
}
this.canDrop = function(dragMode, dataType) {
return true;
}
this.onDragEnterTarget = function(dragMode, type, data) {
}
this.onDragLeaveTarget = function(dragMode, type, data) {
}
this.onDragInTarget = function(dragMode, type, data) {
}
}
Custom.UI.DropZoneBehavior.registerClass(‘Custom.UI.DropZoneBehavior’,
Sys.UI.Behavior, Sys.UI.IDragSource,
Sys.UI.IDropTarget, Sys.IDisposable);
Sys.TypeDescriptor.addType(‘script’, ‘DropZoneBehavior’,
Custom.UI.DropZoneBehavior);


I need to explain this class a bit backwards. The first thing worth noticing is the second to last line that begins with “Custom.UI.DropZoneBehavior.registerClass“. This is where the dropZoneBehaviorClass defined above gets registered with Atlas. The first parameter of the registerClass method takes the name of the class. The second parameter takes the base class. The remaining parameters take the interfaces that are implemented by the new class. The line following this makes your class available for declarative markup scripting. Now back to the top, the “Type.registerNamespace” method allows you to register your custom namespace. The next line declares our new class using an anonymous method syntax. This is a way of writing JavaScript that I am not particularly familiar with, but is very important for making JavaScript object oriented, and is essential for designing Atlas behaviors. Within the anonymous method, the class methods Initialize, Dispose, and getDescriptor are simply standard methods used for all behavior classes, and in this implementation, all you need to do is call the base method (that is, the method of the base class that you specify in the second to last line of this code sample.) The only thing special you do is to register the drop target with the Sys.UI.DragDropManager in the Initialize method. This is the act that makes much of the drag drop magic happen.


Next, you implement the IDropTarget methods. In this example, you are only implementing two methods, “this.canDrop” and “this.drop“. For “canDrop“, you are just going to return true. More interesting logic can be placed here to determine which floating div tags can actually be dropped on a given target, and even to determine what sorts of floating divs will do what when they are dropped; but in this case, you only want a bare-bones implementation of IDropTarget that will allow any floating div to be dropped on it. Your implementation of the “drop” method is similarly bare bones. When a floating element is dropped on one of your drop targets, an alert message will be thrown indicating that something has occurred. And that’s about it. You now have a drop behavior that works with the floating behavior we used in the previous examples.


You should now write up a page to show off your new custom dropzone behavior. You can build on the previous samples to accomplish this. In the Atlas Script Manager, besides registering the AtlasUIDragDrop script, you will also want to register your new DropZoneBehavior script:


<atlas:ScriptManager ID=”ScriptManager1″ runat=”server”>
<Scripts>
<atlas:ScriptReference ScriptName=”AtlasUIDragDrop” />
<atlas:ScriptReference Path=”scriptLibrary/DropZoneBehavior.js” />
</Scripts>
</atlas:ScriptManager>

Next, you will want to add a new div tag to the HTML body, that can be used as a drop target:


<div style=”background-color:Red;height:200px;width:200px;”>
<div id=”draggableDiv” style=”height:100px;width:100px;background-color:Blue;”>
<div id=”handleBar” style=”height:20px;width:auto;background-color:Green;”>
</div>
</div>
</div>

<div id=”dropZone” style=”background-color:cornflowerblue;height:200px;width:200px;”>
Drop Zone
</div>


Finally, you need to add a declarative markup element to add your custom DropZone behavior to the div you plan to use as a dropzone element. The XML markup should look like this:


<script type=”text/xml-script”>
<page xmlns:script=”http://schemas.microsoft.com/xml-script/2005″>
<components>
<control id=”dropZone”>
<behaviors>
<DropZoneBehavior/>
</behaviors>
</control>
<control id=”draggableDiv”>
<behaviors>
<floatingBehavior handle=”handleBar”/>
</behaviors>
</control>
</components>
</page>
</script>

The code you have just written should basically add a dropzone to the original declarative drag and drop example. When you drop your drag element on the dropzone, an alert message should appear. You can expand on this code to make the drop method of your custom dropzone behavior do much more interesting things, such as firing off other JavaScript events in the current page, or even calling a webservice, using Atlas, that will in turn process server-side code for you.

III. Dynamic Drag Drop


 


Since the declarative model is much cleaner than the imperative model, why would you ever want to write your own JavaScript to handle Atlas behaviors? You might want to roll your own JavaScript if you want to add behaviors dynamically. One limitation of the declarative model is that you can only work with objects that are initially on the page. If you start adding objects to the page dynamically, you cannot add the floating behavior to them using the declarative model. With the imperative model, on the other hand, you can.


Building on the previous example, you will replace the “pageLoad()” function with a function that creates floating divs on demand. The following JavaScript function will create a div tag with another div tag embedded to use as a handlebar, then insert the div tag into the current page, and finally add floating behavior to the div tag:


function createDraggableDiv() {
var panel= document.createElement(“div”);
panel.style.height=“100px”;
panel.style.width=“100px”;
panel.style.backgroundColor=“Blue”;
var panelHandle = document.createElement(“div”);
panelHandle.style.height=“20px”;
panelHandle.style.width=“auto”;
panelHandle.style.backgroundColor=“Green”;
panel.appendChild(panelHandle);
var target = $(‘containerDiv’).appendChild(panel);
addFloatingBehavior(panel, panelHandle);
}

You will then just need to add a button to the page that calls the “createDraggableDiv()” function. The new HTML body should look something like this:


<input type=”button” value=”Add Floating Div” onclick=”createDraggableDiv();” />
<div id=”containerDiv” style=”background-color:Purple;height:800px;width:600px;”/>

This will allow you to add as many draggable elements to your page as you like, thus demonstrating the power and flexibility available to you once you understand the relationship between using Atlas declaratively and using it programmatically. As a point of reference, here is the complete code for the dynamic drag and drop example:


<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>Imperative Drag and Drop II</title>
<script type=”text/javascript”>
function createDraggableDiv() {
var panel= document.createElement(“div”);
panel.style.height=”100px”;
panel.style.width=”100px”;
panel.style.backgroundColor=”Blue”;
var panelHandle = document.createElement(“div”);
panelHandle.style.height=”20px”;
panelHandle.style.width=”auto”;
panelHandle.style.backgroundColor=”Green”;
panel.appendChild(panelHandle);
var target = $(‘containerDiv’).appendChild(panel);
addFloatingBehavior(panel, panelHandle);
}
function addFloatingBehavior(ctrl, ctrlHandle){
var floatingBehavior = new Sys.UI.FloatingBehavior();
floatingBehavior.set_handle(ctrlHandle);
var dragItem = new Sys.UI.Control(ctrl);
dragItem.get_behaviors().add(floatingBehavior);
floatingBehavior.initialize();
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<atlas:ScriptManager ID=”ScriptManager1″ runat=”server”>
<Scripts>
<atlas:ScriptReference ScriptName=”AtlasUIDragDrop” />
</Scripts>
</atlas:ScriptManager>
<h2>Imperative Drag and Drop Code with javascript:
demonstrate dynamic loading of behaviors</h2>
<input type=”button” value=”Add Floating Div” onclick=”createDraggableDiv();” />
<div id=”containerDiv” style=”background-color:Purple;height:800px;width:600px;”/>
</form>
</body>
</html>

Authentically Virtual