拾荒时代------技术,艺术!

.NET/Ajax/C#/Web2.0精品技术文章网摘。

2007年7月30日 #

Visual Studio Code Name "Orcas" Express Editions

Visual Studio Code Name "Orcas" Express Editions

2007-5-10
Step 1
The next version of Visual Studio, Microsoft Visual Studio code name “Orcas”, will provide an industry-leading developer experience for Windows Vista, the 2007 Microsoft Office system, and the Web. In addition, it will continue in the Microsoft tradition of development language innovation.See An Overview of Microsoft Visual Studio code name “Orcas” for more detail.
Visual Basic
Easy-to-use development experience including visual designers, intuitive drag-and-drop interface designer and built-in support for Windows XP and Windows Vista Themes.
Fully integrated support of Microsoft SQL Server 2005 Compact Edition.
Harness the latest .NET technology including LINQ, WCF and WPF.
Access a community of millions of other hobbyists, students and game developers to share ideas and create fun samples.
Get started developing WCF applications like an RSS screen saver or a peer-to-peer PictureShare.
Visual C#
Easy-to-use development experience including visual designers, intuitive drag-and-drop interface designer and built-in support for Windows XP and Windows Vista Themes.
Fully integrated support of Microsoft SQL Server 2005 Compact Edition.
Harness the latest .NET technology including LINQ, WCF and WPF.
Access a community of millions of other hobbyists, students and game developers to share ideas and create fun samples.
Get started developing WCF applications like an RSS screen saver or a peer-to-peer PictureShare.
Visual Web Developer
Easy-to-use development experience including visual designers, intuitive drag-and-drop interface designer and support for the latest .NET technology like LINQ.
Easily share your Web applications with friends using the built-in copy-Web functionality.
Access a community of millions of other hobbyists, students and enthusiasts to share ideas and create fun samples on ASP.NET.
Get started with fully functional sample application starter kits designed to help you learn ASP.NET 2.0 including:
Personal Web Site Starter Kit – take advantage of a complete, ready-to-run, ready-to-customize Web site for sharing photos and photo albums.
Club Web Site Starter Kit – create a dynamic Web site for your club or organization featuring contacts, events calendar, photo sharing and more.
Visual C++
Easy-to-use development experience including visual designers, intuitive drag-and-drop interface designer and built-in support for Windows XP and Windows Vista Themes.
Ideal for gamers:
Create your own mods for popular games.
Learn from the Pros by downloading source code to commercial games such as Quake or Microsoft Allegiance.
Develop high-performance games like Vertigo Software's Quake II .NET, a port of the Quake 3D engine for Visual C++.
Harness the coolest Windows Vista features and the latest Windows Platform SDK.

posted @ 2007-07-30 00:44 拾荒时代 阅读(361) 评论(0) 编辑

2007年7月25日 #

C#好书盘点

作者:清清月儿

主页:http://blog.csdn.net/21aspnet/           时间:2007.7.7 

本文本人只授权CSDN以及其相关单位机构随意修改,其他任何出版机构,博客可以转载但是要保留版权如果修改版权信息,本人将根据《信息网络传播权保护条例》追究法律责任,请尊重他人的劳动成果,尊重原创!

C#是学习asp.net和.NET Winform程序的基础,所以一定要学好。从00年C#出道到现在,7年过去了,C#的书出了许多,有不少好书。

1.《21天学通C# 》

作者:作者:(美)琼斯 著,信达工作室 译    出版社:人民邮电出版社 出版日期:2002-3-1

点评:这本书出版于02年,现已成绝版孤本,书店已经没有,只有高校的图书馆有此书的芳踪了。个人认为这本书是入门的最好书籍,因为这本书讲的最浅显,厚度也可以,没有比这更浅显的书了,当然这本书浅则浅亦却不是肤浅而是从最浅显的入手讲述深刻的道理。书中的例子都给的很全,初学者还是非常适合读这本书的,把基础的东西讲的很透彻。属于sam公司的21天系列,这本书还有个好处就是章节安排是本人见过最合理的,不想某些书感觉很乱。书基本是讲语法,后面安排2章讲了WINFORM和ASPNET,个人觉得很好,其实在目前的情况下.NET还是做ASP.NET的多,所以没有必要讲WINFORM,WINFORM还是用C++或者VB或者其他老语言吧,因为.NET的代码可以被反编译,所以估计没有人愿意这样公开自己代码吧,ASP.NET就不一样了,代码在服务器上。初学者最主要的是要树立一个好的知识框架,不会没有关系,但是要知道前后关系。 本书缺点是讲1.1的。

 2.《C#程序设计》

作者:美 利伯蒂 编著 刘基诚 译 出版社:中国电力出版社 出版日期:2002-4-1

点评:也是一本孤本绝版,不过好在本书第4版即将出版(估计讲C#2.0的),这本书和上一本很像,不过这本书比上一本书讲的“难”,有一点深度,前几章可能还好,可能到后面就发现作者显山漏水了。 本书的作者Jessy Liberty还出过一本书,Programming ASP.Net,也是O'Reilly出版的,年初出版的,写的很基础,Jesse写的书比较易懂!本书翻译的也不错。书中“委托”被翻译为“代表”,这也是“委托”叫的很少的一种说法。这本书也是因为结构合理所以算是好书。

3.《C#入门经典(第3版)》

作者:(美)Karli Watson Christian Nagel 等著 出版社:清华大学出版社 出版日期:2006-5-1

点评:这本书先后出了2版,就个人来说觉得没有上2本书章节安排的合理,难度相对第一本书稍微大了一点点,但是这不影响它成为经典,书不错,基础点都讲到了,此书一定要看,估计这本书也是看的最多的人。作者清清月儿http://blog.csdn.net/21aspnet/ 泛型也讲到了,XML,ADONET,画图,部署都有点介绍,这本书讲的很全,书也很厚,不过深度不够,很多地方都是介绍性的。以集合那一章为例就没有和泛型很好的结合,只能算开了个头,当然如果作者真的把所有都写的很细估计要在写10本都不够,总之这也是好书,这本书最大的特点是看得人最多,所以买也好,下载也好(下载是1.1版的没有2.0内容),图书馆借也好都会很容易找到这本书

4.《C#高级编程(第4版)》

作者:(美)内格尔 等编著,李敏波 翻译 出版社:清华大学出版社 出版日期:2006-10-1

点评:最厚的一本书,1200页,200万字。这本书讲了很多高级的主题,当然也不够深入,可以看作抛砖引玉吧,前半部分也是讲语法,讲的不错,后面讲了反射,线程,程序集,AD,Remoting,COM互操作,注册表操作等等。既内容详细而且全面,适合初学者也适合高手进阶。不过多人写的书自然有其缺点就是会风格多变,所以结构混乱,这本书和上1本都是的。相对头2本由1人写的就不同了。不过可以把这本书当作MSDN一类的东西看吧。

5.《C# Primer Plus 中文版》

作者:[美]米切尔森 著,云巅工作室 编译      出版社:人民邮电出版社      出版时间:2002年07月

点评:孤本绝版好书。这本书是讲C#语法最细最厚最的,如果你觉得看其他书还看不懂就要看这本书,作者甚至于把例子也一行一行的做了讲解,可以说任何人看这本书没有学不会的!作者清清月儿http://blog.csdn.net/21aspnet/不说别的,光数组就讲了2章,这是其他书中没有看到过的。作者周良忠是畅销图书《C++实践之路》的译者。引用译者的话:你可以想像成一包方便面(入门书),与其他方便面相比,它附加了更多的作料(知识点),制作过程中,还多了几道工序(特有的讲解方式)! 因为该书与其他C#入门书的不同之处是,知识结构完整、为读者顺利学习主知识plus了“油”,也plus了“醋”;但它对知识点的讲解并非深奥难懂,只是在基本编程知识的基础上把C#的要点逐渐plus进来。

6.《C#编程语言详解》

作者:(美)Anders Hejlsberg,Scott Wiltamuth,Peter Golde 著,张晓坤,谭立平,车树良 译      出版社:电子工业出版社      出版时间:2004年09月 

点评:也几乎成孤本绝版了。你可以不知道此书,但是你不应该不知道作者作者Anders Hejlsberg,C#之父,Delphi之父。这本书是当年最早讲C#2.0的书也只有Anders Hejlsberg在那个年代先为大家传道泛型。书中前面讲了1.1的语法后面是2.0的泛型,迭代器,匿名方法。没有设计高级知识。大师就是大师,这本书讲知识点讲滴水不漏,讲的最深,书中文字很枯燥,不知道是不是作者就这么写的。

7.《Visual C# 2005技术内幕》

作者:(美)霍夫曼 著,李虎 等译      出版社:机械工业出版社      出版时间:2007年05月

点评:这是一本很的书,这本书个人看了觉得很好,书不厚却包罗万象!语法讲到了,也讲了多线程,加密公钥私钥,对于ADO.NET更是用了5章,不同于其他书籍,所以也可以看出作者偏向于应用。对于Asp.net的WebPart和用户定制主控页都做了几章讲了,最后也讲了Winform。个人觉得这本书是最好的一本书,不厚却很精华。作者http://blog.csdn.net/21aspnet/

7.《Visual C# 2005技术内幕》

作者:(美)马歇尔 著,许华杰,刘光惠 译      出版社:清华大学出版社      出版时间:2007年01月 

点评:和上一本一样的名字,黑皮书,个人觉得这本书叫技术内幕似乎更合适,上一本叫技术大全才合适。微软出的自然说明书不会差,一般微软出的书都有某种用意,属于较高端的书。这本书最大的特点是作者喜欢大而全,和其他的大而全比作者用列表的方式列出知识点的全部属性,所以可以把这本书当作MSDN的浓缩版看吧。

8.《Visual C# 2005从入门到精通》

作者:(英)夏普 著,周靖 译      出版社:清华大学出版社      出版时间:2006年06月

点评:2.0好书,讲的很深很好,章节安排很好,缺点是讲的不够多,虎头蛇尾了,前面的基本语法堪称完美,挑不出任何毛病,不过后面部分感觉作者在糊任务,个人感觉后半部可以删除。作者讲到的部分都可以说讲的是其他书相比最的,这本书有个特点例子很深。书中例子讲了源码读取器,就是代码收缩自动标注颜色,可见作者水平很深。这本书还是值得读的。

9.《框架设计(第2版):CLR VIA C#》

作者:(美)瑞奇特(Richter,J.) 著,周靖,张杰良 译      出版社:清华大学出版社      出版时间:2006年11月 

点评:Jeffrey Richter是一位在全球享有盛誉的技术作家,尤其在Windows/.NET领域有着杰出的贡献。他的第一本Windows著作Windows 3: A Developer's Guide大获好评,从而声名远扬。之后,他又推出了经典著作《Windows 高级编程指南》和《Windows核心编程》。如今这两本书早已成为Windows程序设计领域的颠峰之作,培育了几代软件开发设计人员。他的每一本新作问世,我们都有理由相信这是一本巨著,我们想要的一切尽在其中。

这本书主要讲.NET框架的核心知识,表面上看也是写数组,接口,委托,泛型,异常,垃圾回收等等,但是这本书的深度是其他书不可比拟的,这本书一定要看,但是不适合初学者。

10.《.NET本质论第1卷:公共语言运行库》

作者:Don Box(美)伯克斯,(美)赛欧司编 著,张晓坤 译      出版社:中国电力出版社      出版时间:2004年04月

点评:Don Box 是一位著名的教育家,被公认为组件对象模型(COM) 领域的权威人物!本书讲了.NET精髓CLR的运行原理,很深,绝对不适合初学者!初学者一定不要看,但是水平高的一定要看!DON BOX的书文字教晦涩。

11.《NET设计规范:.NET约定、惯用法与模式》

作者:克瓦林纳,艾布拉姆斯 著,葛子昴 译      出版社:人民邮电出版社      出版时间:2006年07月

点评:作为高端的书,其实在看了很多书以后写代码规范就要提到日程上,但是本书作者又不是纯粹讲规范而是讲为什么要这样,其实可以把这一本书看作是讲C#语法的高端书,书中包含很多评注,揭示了很多历史背景,可见译者很有功底,译者在微软工作,从某种角度来说这本书的价值可能更胜过《设计模式》这本书,作者是参与.NET Framework 的设计者,有丰富的经验,书中的建议可以说都是建立在大部分开发人员都熟悉的Framework来讲解更加让人易于理解!Anders Hejlsberg,C#之父给本书高度评价:在微软,本书所讲述的规范已经指导我们经历了.NET框架三个版本和无数其他项目的开发。而且它正指导着下一代Windows操作系统API--WinFX的开发!

 

posted @ 2007-07-25 19:49 拾荒时代 阅读(297) 评论(1) 编辑

VS 2008 Web Designer and CSS Support

VS 2008 Web Designer and CSS Support

One of the big features that web developers will quickly discover with VS 2008 is its dramatically improved HTML designer, and the rich CSS support it brings. 

VS 2008 now uses the same web designer that ships with Microsoft's new Expression Web product.  In addition to providing lots of new functionality, you'll also find that this web designer is much faster than the VS 2005 version (which was based on a much older code base).

Below is a quick tour of some of the new web designer features that you'll be able to take advantage of with both VS 2008 as well as the free Visual Web Developer 2008 Express:

Split View Editing

In addition to supporting both source-view and design-view, VS 2008 adds support for a new "split-view" mode when working on pages.  This allows you to see both the HTML source and the Design View at the same-time, and easily have any changes you make in one view be updated in the other:

 

CSS Style Manager

VS 2008 supports a new tool window inside the IDE called "Manage Styles".  This shows all of the CSS stylesheets, and their corresponding rules, for the page you are currently editing.  It can be used both when you are in design-view, as well as when you are in source view on a page:

A circle around a CSS rule in the manage styles window indicates that particular rule is in use within the current document.  Using the mouse to hover over the rule allows you to quickly see the CSS rule values:

You can then either right-click on a CSS rule and select "Modify Style" to bring up a graphical CSS rules editor, or you can double click on the rule in the manage styles window to automatically open the stylesheet file and jump immediately to the CSS source definition to edit (with full intellisense):

For even more tips/tricks about how to best use the "Manage Styles" tool window please read this blog post.

CSS Properties Window

One of the other cool new CSS features that is also supported in both design and source view is the new CSS Properties Window:

When you select an HTML element or ASP.NET server control, the CSS property window will show you all of the CSS settings currently applied to it. You can also change any of the values using the CSS property grid. The "target rule" drop-down in the style toolbar allows you to determine under what rule the settings are applied (read this blog post to learn more about the style toolbar and target rule dropdown). 

If, like me, you sometimes struggle with large CSS stylesheets and find yourself shouting "why the $!#@ is it looking like that?", you'll find the "summary" view of the CSS Properties window really useful (just click the summary button at the top of the CSS properties pane).  When you press this button it enables a filtering mode that shows you the full inheritance set of CSS rules for the current HTML element or ASP.NET control you are working with:

In the properties grid above you'll notice that some values are duplicated multiple times - with red arrows striking out previous values.  This indicates that a parent CSS rule setting is being overridden by another CSS rule's value.  You can see both the original value as well as the overridden one in the summary view at the bottom. 

You can click on the individual values to see where in the CSS precedence hierarchy this value was inherited from or overridden.  In the example below you can see that the final color for the current element that my cursor is on is a dark brown color.  If I select this final color value, the CSS properties window will draw a blue box in the applied-rules list above indicating that this setting is set in the "singlecontent h3" rule:

If I click on the lighter brown color setting that this rule overrode (and which has the red strike-thru), you can see that it originated with the page's HTML body CSS rule (notice how the body rule below is selected in the applied rules list when I select the overridden value below):

Please read this dedicated CSS Properties Window blog post to learn even more how to use the CSS property window.

CSS Source View Intellisense

The HTML designer supports the ability to select an element or control in design-view, and graphically select a rule from the CSS list to apply to it. 

You'll also find when in source mode that you now have intellisense support for specifying CSS class rules:

This is true for both HTML element (like above), as well as with ASP.NET server controls:

This CSS intellisense is supported in both regular HTML / ASP.NET pages, as well as when working with pages based on master pages and nested master pages.

Nested Master Page Support

Earlier this month I wrote a dedicated blog post that covered the new VS 2008 Nested Master Page Support.  All of the above designer and CSS features obviously work with that as well:

Summary

The above post provides a quick look at some of the new HTML designer and CSS tool support in VS 2008 (all of the above features also ship with the free Visual Web Developer 2008 Express edition). 

Because VS 2008 now has multi-targeting support you'll be able to use these feature immediately without having to install .NET 3.5 on your servers.  You can open existing ASP.NET 2.0 projects in VS 2008, have VS 2008 continue to target .NET 2.0 as the runtime target, and begin using these features immediately.

Over the next week I'll also be starting a new multi-part blog series that covers the new <asp:listview> control that ships as part of ASP.NET in .NET 3.5.  One of the big benefits of the <asp:listview> is that it enables developers to have total control over the HTML output emitted in data scenarios.  This works well with all of the new CSS tool features above, and enables you to more easily create great looking web sites and applications.

Hope this helps,

Scott

posted @ 2007-07-25 19:08 拾荒时代 阅读(824) 评论(0) 编辑

VS 2008 Multi-Targeting Support


VS 2008 Multi-Targeting Support

Earlier this month at TechEd we announced the official name of Visual Studio "Orcas" - which will be called Visual Studio 2008.  We also said that the official name for the .NET Framework "Orcas" release will be called .NET Framework 3.5 (it includes the new LINQ support, integrated ASP.NET AJAX support, new ASP.NET data controls, and more).

VS 2008 and .NET 3.5 Beta 2 will ship later this summer, and the Beta 2 release will support a go-live license for those who want to put applications into production using the new features immediately.

What is Multi-Targeting?

With the past few releases of Visual Studio, each Visual Studio release only supported a specific version of the .NET Framework.  For example, VS 2002 only worked with .NET 1.0, VS 2003 only worked with .NET 1.1, and VS 2005 only worked with .NET 2.0.

One of the big changes we are making starting with the VS 2008 release is to support what we call "Multi-Targeting" - which means that Visual Studio will now support targeting multiple versions of the .NET Framework, and developers will be able to start taking advantage of the new features Visual Studio provides without having to always upgrade their existing projects and deployed applications to use a new version of the .NET Framework library.

Now when you open an existing project or create a new one with VS 2008, you can pick which version of the .NET Framework to work with - and the IDE will update its compilers and feature-set to match this.  Among other things, this means that features, controls, projects, item-templates, and assembly references that don't work with that version of the framework will be hidden, and when you build your application you'll be able to take the compiled output and copy it onto a machine that only has an older version of the .NET Framework installed, and you'll know that the application will work.

Creating a New Project in VS 2008 that targets .NET 2.0

To see an example of multi-targeting in action on a recent build of VS 2008 Beta 2, we can select File->New Project to create a new application. 

Notice below how in the top-right of the new project dialog there is now a dropdown that allows us to indicate which versions of the .NET Framework we want to target when we create the new project.  If I keep it selected on .NET Framework 3.5, I'll see a bunch of new project templates listed that weren't in previous versions of VS (including support for WPF client applications and WCF web service projects):

If I change the dropdown to target .NET 2.0 instead, it will automatically filter the project list to only show those project templates supported on machines with the .NET 2.0 framework installed:

If I create a new ASP.NET Web Application with the .NET 2.0 dropdown setting selected, it will create a new ASP.NET project whose compilation settings, assembly references, and web.config settings are configured to work with existing ASP.NET 2.0 servers:

When you go to the control Toolbox, you'll see that only those controls that work on ASP.NET 2.0 are listed:

And if you choose Add->Reference and bring up the assembly reference picker dialog, you'll see that those .NET class assemblies that aren't supported on .NET 2.0 are grayed out and can't be added to the project (notice how the "ok" button is not active below when I have a .NET 3.0 or .NET 3.5 assembly selected):

So why use VS 2008 if you aren't using the new .NET 3.5 features?

You might be wondering: "so what value do I get when using VS 2008 to work on a ASP.NET 2.0 project versus just using my VS 2005 today?"  Well, the good news is that you get a ton of tool-specific value with VS 2008 that you'll be able to take advantage of immediately with your existing projects without having to upgrade your framework/ASP.NET version.  A few big tool features in the web development space I think you'll really like include:

  1. JavaScript intellisense
  2. Much richer JavaScript debugging
  3. Nested ASP.NET master page support at design-time
  4. Rich CSS editing and layout support within the WYSIWYG designer
  5. Split-view designer support for having both source and design views open on a page at the same time
  6. A much faster ASP.NET page designer - with dramatic perf improvements in view-switches between source/design mode
  7. Automated .SQL script generation and hosting deployment support for databases on remote servers

You'll be able to use all of the above features with any version of the .NET Framework - without having to upgrade your project to necessarily target newer framework versions.  I'll be blogging about these features (as well as the great new framework features) over the next few weeks.

So how can I upgrade an existing project to .NET 3.5 later?

If at a later point you want to upgrade your project/site to target the NET 3.0 or NET 3.5 version of the framework libraries, you can right-click on the project in the solution explorer and pull up its properties page:

You can change the "Target Framework" dropdown to select the version of the framework you want the project to target.  Doing this will cause VS to automatically update compiler settings and references for the project to use the correct framework version.  For example, it will by default add some of the new LINQ assemblies to your project, as well as add the new System.Web.Extensions assembly that ships in .NET 3.5 which delivers new ASP.NET controls/runtime features and provides built-in ASP.NET AJAX support (this means that you no longer need to download the separate ASP.NET AJAX 1.0 install - it is now just built-in with the .NET 3.5 setup):

Once you change your project's target version you'll also see new .NET 3.5 project item templates show up in your add->new items dialog, you'll be able to reference assemblies built against .NET 3.5, as well as see .NET 3.5 specific controls show up in your toolbox. 

For example, below you can now see the new <asp:listview> control (which is an awesome new control that provides the ability to do data reporting, editing, insert, delete and paging scenarios - with 100% control over the markup generated and no inline styles or other html elements), as well as the new <asp:linqdatasource> control (which enables you to easily bind and work against LINQ to SQL data models), and <asp:datapager> control show up under the "Data" section of our toolbox:

Note that in addition to changing your framework version "up" in your project properties dialog, you can also optionally take a project that is currently building against .NET 3.0 or 3.5 and change it "down" (for example: move it from .NET 3.5 to 2.0).  This will automatically remove the newer assembly references from your project, update your web.config file, and allow you to compile against the older framework (note: if you have code in the project that was written against the new APIs, obviously you'll need to change it).

What about .NET 1.0 and 1.1?

Unfortunately the VS 2008 multi-targeting support only works with .NET 2.0, .NET 3.0 and .NET 3.5 - and not against older versions of the framework.  The reason for this is that there were significant CLR engine changes between .NET 1.x and 2.x that make debugging very difficult to support.  In the end the costing of the work to support that was so large and impacted so many parts of Visual Studio that we weren't able to add 1.1 support in this release. 

VS 2008 does run side-by-side, though, with VS 2005, VS 2003, and VS 2002.  So it is definitely possible to continue targeting .NET 1.1 projects using VS 2003 on the same machine as VS 2008. 

What is compatibility like moving from VS 2005 to VS 2008 and .NET Framework 2.0 to 3.5?

We are trying to make sure that .NET Framework 3.5 is a super compatible upgrade from .NET 2.0, and not require you to change any code in order to target the new framework version.  We've deliberately made only non-breaking modifications to existing .NET assemblies in the .NET 3.5 release, and where possible added new features in separate assemblies to minimize the chance of breaking changes.

We are also not making project model or build changes with VS 2008.  I, like you, hope to never to go through that again!  Both the "web site" and "web application project" models will be fully supported going forward.

Hope this helps,

Scott

///////////////////////////////// 浏览器

posted @ 2007-07-25 15:58 拾荒时代 阅读(299) 评论(0) 编辑

VS 2008 JavaScript Intellisense


VS 2008 JavaScript Intellisense

One of the features that web developers will really like with VS 2008 is its built-in support for JavaScript intellisense.  This is enabled in both the free Visual Web Developer 2008 Express edition as well as in Visual Studio, and makes using JavaScript and building AJAX applications significantly easier. 

Below is a quick tour of some of the new JavaScript intellisense features to take advantage of:

JavaScript Type Inference

One of the things you'll notice immediately when you start typing within a script block is the richer support that Visual Studio 2008 now has for JavaScript keywords and language features:

JavaScript is a dynamic language, and doesn't support explicit type declarations, which has made implementing good intellisense difficult in the past.

Visual Studio 2008 adds support for type inference, which means that it evaluates and computes how a JavaScript block is being used and dynamically infers the variable usage and type information of the code to provide accurate intellisense support.

For example, Visual Studio below will infer that an html element is being retrieved by the document.getElementById() method, and provide appropriate html element intellisense for the variable result:

If I later assign a numeric value to the "myElement" variable (which in JavaScript converts it to a number), notice how VS will detect this and now provide integer intellisense for the variable later in the method:

Intellisense for External JavaScript Libraries

VS 2008 supports intellisense not just for in-line script, but also for externally referenced JavaScript files.  For example, assume we have a "getMessage" function like below defined within a "Util.js" javascript file:

I can then simply add a standard JavaScript script refrence element to my page, and I will then automatically receive intellisense support for it as I code:

Notice how VS automatically provides basic parameter intellisense information on the method without us having to do anything special to the JavaScript for it to appear:

Adding Intellisense Hints to JavaScript

As you saw above, Visual Studio will automatically provide basic intellisense help information for the method name and parameters of standard JavaScript.

You can optionally make this intellisense richer by adding comments to your JavaScript code that the intellisense engine can then pick up and use when you consume a method or library.  For example, I could add the below comments to the getMessage function in my util.js file:

And when I then code against it within my "Default.aspx" file Visual Studio will automatically display this summary information for the method:

As well as the parameter details:

We'll provide a tool that then allows you to automatically strip out your comments (and compress the whitespace and size) of your JavaScript once you've finished building your application.  For more details about the comment format that both VS and ASP.NET AJAX support, please read Bertrand Le Roy's post here.

Intellisense within External JavaScript files

Obviously you get full intellisense support within external JavaScript files, just like you do within script blocks inside .htm and .aspx files.

One of the interesting characteristics about external JavaScript files is that they can call and use the JavaScript functions and variables declared within other JavaScript files that a page loads. 

For example, if we declare two external Javascript files referenced on a page like so:

The JavaScript code within the "MyLibrary.js" javascript file will be able to call the methods declared within the Util.js file.

You can tell Visual Studio to provide intellisense for the "Util.js" library within the "MyLibrary.js" file by adding a /// <reference> comment at the top of the external library.  Once you do this, you'll get full intellisense support for those methods and variables:

This ends up being super useful when partitioning your JavaScript routines across multiple files.

To reference the ASP.NET AJAX client side JavaScript libraries, you can either add a <refrence> that points to your own copy of the .JS file (if you are manually including it in your project), or add a <reference> element with a name value if the library is being dynamically output by the <asp:scriptmanager> control on the host page:

Once you do this you'll get full intellisense for all of the JavaScript libraries and type-library patterns inside ASP.NET AJAX.

Calling Web Services using ASP.NET AJAX

ASP.NET AJAX makes it easy to expose methods on the server that can be called and accessed via client-side JavaScript.  For example, assume we define a simple webmethod in a .asmx web-service like below:

I could then have ASP.NET AJAX automatically create a client-side JavaScript proxy object that uses the JSON protocol to call and use it from the client by adding a reference to it with a <asp:scriptmanager> control in my page like below:

What is cool about VS 2008 is that when you declare a reference to a web-service using the <asp:scriptmanager> control like above, it will add client JavaScript intellisense support for it within the page automatically:

Obviously this makes it much easier to identify methods on the server and asynchronously call and invoke them.  You can use this to both exchange data between the client and server.  You can also use the AJAX UI templating technique I described here to retrieve HTML UI from the server using these callbacks and then dynamically update the page with them.

Creating Re-Usable ASP.NET AJAX Behaviors, Controls and Libraries

ASP.NET AJAX provides type-system support within JavaScript for defining classes, interfaces, and other object oriented concepts.  This makes it much easier to define re-usable libraries of JavaScript that encapsulate functionality and re-use it safely across pages and applications (without having to worry about the JavaScript conflicting with other JavaScript or libraries).

VS 2008 provides new "Add-Item" templates that makes it easy to create new ASP.NET AJAX behaviors, controls and libraries:

ASP.NET AJAX uses the "prototype" pattern within JavaScript to enable you to define classes and interfaces.  For example, I can create an encapsulated JavaScript class using this pattern using one of the project item templates above (notice below how the namespace created by Visual Studio by default is the same as my project namespace):

Obviously I then get full intellisense support when consuming my new library from any page or other JavaScript file:

Summary

Hopefully the above walkthrough provides a first look at some of the new JavaScript intellisense features coming soon (there are more - but this is a start).  In future blog-posts I'll also cover some of the new JavaScript debugging features that VS 2008 brings, as well as some of the WYSIWYG designer support for ASP.NET AJAX and the ASP.NET AJAX Control Toolkit.

To learn more about ASP.NET AJAX (and how you can use all of the runtime features I described above starting today with ASP.NET 2.0), I'd also highly recommend checking out these two new books that have recently been published and which cover the official ASP.NET AJAX 1.0 release:

Note that because of the new VS 2008 multi-targeting support, you can use the JavaScript intellisense features I showed above with both ASP.NET applications built using .NET 3.5 (which has ASP.NET AJAX built-in), as well as with existing ASP.NET 2.0 applications (including ones that use the separate ASP.NET AJAX 1.0 download). This provides a very compelling reason to start using VS 2008 - even if you are using it to only target .NET 2.0 applications.

Hope this helps,

Scott


posted @ 2007-07-25 15:56 拾荒时代 阅读(512) 评论(0) 编辑

Updated ASP.NET AJAX Control Toolkit Release and New ASP.NET AJAX Videos/Articles


浏览器

Updated ASP.NET AJAX Control Toolkit Release and New ASP.NET AJAX Videos/Articles

Last week the ASP.NET AJAX Control Toolkit team released Build 10618 of the ASP.NET AJAX Control Toolkit.  This fixed a few issues discovered with the release earlier this month including:

  • A fix for the Tabs naming container
  • A fix for a VS design-time dependency
  • FilteredTextBox Navigation and control key issues

This build also contains additional performance optimizations for the new "script combining" feature provided by the new ToolkitScriptManager control.  This feature can help significantly improve performance for pages with multiple AJAX scripts that previously needed to be downloaded separately.  David Anson has a nice blog post that talks about these improvements here.

New ASP.NET AJAX Videos

Joe Stagner has recently posted five new (free) ASP.NET AJAX videos on www.asp.net:

You can download and watch the videos here.  These new videos are available to download in a variety of video and audio formats including: WMV, Zune, iPod, PSP, MPEG-4, and 3GP.

New ASP.NET AJAX Articles

Here are a few recent ASP.NET AJAX articles you might also want to check out:

  • ASP.NET AJAX UpdatePanel Tips and Tricks: This is a great MSDN Magazine article by Jeff Prosise that covers: update highlighting, how to cancel updatepanel updates, optimizing with conditional updatepanels, and using page methods.
  • AJAX Control Toolkit Patch Utility: If you are not an official contributor to the ASP.NET AJAX Control Toolkit project, but would like to submit a bug fix or small feature into the toolkit, you can read this article to learn how to create and submit a patch to the team for them to review and potentially include.

ASP.NET AJAX 1.0 Books

As I've mentioned in other recent posts, the first books specifically targeting the final ASP.NET AJAX 1.0 release were recently published.  Below are links to two of them that are shipping today:

Both books also include a chapter on using the controls within the ASP.NET AJAX Control Toolkit.

Hope this helps,

Scott

posted @ 2007-07-25 15:52 拾荒时代 阅读(379) 评论(0) 编辑

July 4th Links: ASP.NET, ASP.NET AJAX, Visual Studio, Silverlight and IIS7


I've fallen behind on my weekly link-listing series - apologies for the delay.

ASP.NET

  • ASP.NET RSSToolkit 2.0 Released: One of the cool projects for ASP.NET 2.0 that was released last year was this free RSS Toolkit - which makes consuming and exposing RSS feeds in ASP.NET super easy (you can even databind any ASP.NET control against them).  The team working on the CodePlex project has recently released V2 of the RSSToolkit.  You can learn all about it and download it here.

  • Building a Custom Database Driven Site Map Provider: Scott Mitchell has written a great article on how to implement your own site map provider for ASP.NET that is populated from a database (instead of statically from an XML file).  You can learn more about the ASP.NET 2.0 SiteMap system from this older blog post of mine here.

  • .NET DateTime and Number Format String Cheat Sheet: If you are like me, you might have trouble remembering all of the standard format strings you can pass to the String.Format() method and/or the Eval() databinding method in ASP.NET to generate the appropriate string output from a DateTime or Numeric datatype.  This PDF cheatsheet is a useful one to download and save to quickly look these format strings up.  John has some other really useful .NET PDF cheatsheets he has also created that you might like to download here.

  • Profile Support for ASP.NET Web Application Projects: VS 2005 Web Application Projects can't directly access the strongly-typed ASP.NET "Profile" object that web site projects support.  This VS add-in supports the ability to generate a strongly typed profile class to accomplish this.  You can read this great series of posts to learn more about how to use the ASP.NET 2.0 Profile system.  I have it on my list of tips/tricks posts to-do to cover using this VS add-on as well.

  • ASP.NET Photo Handler: Bertrand has posted a cool photo album HttpHandler for ASP.NET that allows you to easily drop images into a web directory and automatically generate a nice photo album of them (complete with EXIF information, stack sorting icons, etc).  Might be very useful for people enjoying holidays this summer.  Download the code here.

  • BlogEngine.NET: This is a new open source blog engine for ASP.NET that Mads Kristensen has helped start up, and which I've heard a lot of good things about.  You can read about its features here, and download it here.

ASP.NET AJAX

  • ScriptDoc 1.0 Available: Bertrand Le Roy has published a cool ScriptDoc utility that extracts documentation from JavaScript files and packages it into XML that can be consumed by documentation building tools.  A very useful tool as you start to build up your own JavaScript libraries.

Visual Studio

  • GhostDoc 2.1.1 Released: GhostDoc is a free add-in for Visual Studio 2005 (and now 2008) that automatically generates default XML documentation comments for code you write in C# or VB.  It can automatically re-use existing documentation inherited from base classes or implemented interfaces, or generate initial documentation by deducing comments from the name and type of the member signature. You can learn more about it and download it for free here.

Silverlight

  • Silverlight Tutorials: Michael Schwarz has a great blog where he writes regularly about Silverlight.  This tutorials link points to a bunch of great Silverlight content.

IIS 7

  • IIS 7.0 is now running all of Microsoft.com: One of the things we push at Microsoft is to "dogfood" our products on our high volume sites when they enter the beta cycle.  As of a few weeks ago, all of the web servers running www.microsoft.com are now running on IIS7 and Windows 2008 Server Beta3.  These servers host 500+ virtual roots and 350 ASP.NET applications, and handle 300,000 concurrent connections.  IIS7 is going to be an awesome release.

  • IIS 7.0 on Server Core: Bill Staples blogs about some of the new IIS7 enhancements that appear with the June CTP of Windows 2008 Server.  One of the big features that is now supported is the ability to install IIS7 on "server core" - which is a low footprint installation of Windows 2008 Server that lays down just the minimal footprint needed to boot (meaning no GUI shell).  This lowers the resources required on servers, and even more importantly means that servers don't need to be updated if a patch is released for a component not installed on the server (which lowers the downtime of servers).  ASP.NET and the .NET Framework aren't supported yet in server core configurations - but will be in the future.

Hope this helps,

Scott

P.S. I'm out on vacation this week, so please excuse delays on email and comment feedback.

posted @ 2007-07-25 15:50 拾荒时代 阅读(399) 评论(0) 编辑

LINQ to SQL (Part 5 - Binding UI using the ASP:LinqDataSource Control)

Over the last few weeks I've been writing a series of blog posts that cover LINQ to SQL.  LINQ to SQL is a built-in O/RM (object relational mapper) that ships in the .NET Framework 3.5 release, and which enables you to easily model relational databases using .NET classes.  You can use LINQ expressions to query the database with them, as well as update/insert/delete data.

Below are the first four parts of my LINQ to SQL series:

In these previous LINQ to SQL blog posts I focused on how you can programmatically use LINQ to SQL to easily query and update data within a database.

In today's blog post I'll cover the new <asp:LinqDataSource> control that is shipping as part of ASP.NET in the upcoming .NET 3.5 release.  This control is a new datasource control for ASP.NET (like the ObjectDataSource and SQLDataSource controls that shipped with ASP.NET 2.0) which makes declaratively binding ASP.NET UI controls to LINQ to SQL data models super easy.

Sample Application We'll be Building

The simple data editing web application I'll walkthrough building in this tutorial is a basic data entry/manipulation front-end for products within a database:

The application will support the following end-user features:

  1. Allow users to filter the products by category
  2. Allow users to sort the product listing by clicking on a column header (Name, Price, Units In Stock, etc)
  3. Allow users to skip/page over multiple product listings (10 products per page)
  4. Allow users to edit and update any of the product details in-line on the page
  5. Allow users to delete products from the list

The web application will be implemented with a clean object-oriented data model built using the LINQ to SQL ORM.

All of the business rules and business validation logic will be implemented in our data model tier - and not within the UI tier or in any of the UI pages.  This will ensure that: 1) a consistent set of business rules are used everywhere within the application, 2) we write less code and don't repeat ourselves, and 3) we can easily modify/adapt our business rules at a later date and not have to update them in dozens of different places across our application.

We will also take advantage of the built-in paging/sorting support within LINQ to SQL to ensure that features like the product listing paging/sorting are performed not in the middle-tier, but rather in the database (meaning only 10 products are retrieved from the database at any given time - we are not retrieving thousands of rows and doing the sorting/paging within the web-server). 

What is the <asp:LinqDataSource> control and how does it help?

The <asp:LinqDataSource> control is an ASP.NET control that implements the DataSourceControl pattern introduced with ASP.NET 2.0.  It is similar to the ObjectDataSource and SqlDataSource controls in that it can be used to declaratively bind other ASP.NET controls on a page to a datasource.  Where it differs is that instead of binding directly to a database (like the SqlDataSource) or to a generic class (like the ObjectDataSource), the <asp:linqdatasource> is designed to bind against a LINQ enabled data model.

One of the benefits of using the <asp:linqdatasource> control is that it leverages the flexibility that LINQ based ORMs provide.  You don't need to define custom query/insert/update/delete methods for the datasource to call - instead you can point the <asp:linqdatasource> control at your data model, identify what entity table you want it to work against, and then bind any ASP.NET UI control against the <asp:linqdatasource> and have them work with it.

For example, to get a basic product listing UI on my page that works against Product entities within a LINQ to SQL data model, I could simply declare a <asp:linqdatasource> on my page that points to my LINQ to SQL datacontext class, and identify the entities (for example: Products) in the LINQ to SQL data model I want to bind against.  I could then point a GridView at it (by settings its DataSourceID property) to get a grid-like view of the Product content:

Without having to-do anything else, I can run the page and have a listing of my Product data with built-in support for paging and sorting over the data.  I can add a edit/delete button on the Grid and automatically have update support as well.  I don't need to add any methods, map any parameters, or write any code for the <asp:LinqDataSource> to handle both these querying and updating scenarios - it can work against the LINQ to SQL data model we point it against and do these operations automatically.  When updates are made, the LINQ to SQL ORM will automatically ensure that all business rules and validation logic we've added (as partial methods) to the LINQ to SQL data model pass before persisting anything to the database.

Important: The beauty of LINQ and LINQ to SQL is that it obviously isn't tied to being used only in UI scenarios - or with particular UI binding controls like the LinqDataSource.  As you've seen in my previous posts in this series, writing code using the LINQ to SQL ORM is extremely clean.  You can always write custom UI code to directly work against your LINQ to SQL data model if you prefer, or when you find a UI scenario that isn't particularly suited to using the <asp:linqdatasource>. 

The below sections walkthrough using LINQ to SQL and the <asp:LinqDataSource> control to build the web application scenario I defined above.

Step 1: Define our Data Model

We'll begin working on the application by first defining the data model we'll use to represent our database. 

I discussed how to create a LINQ to SQL data model using VS 2008's LINQ to SQL designer in Part 2 of this series.  Below is a screenshot of the data model classes I can quickly create using the LINQ to SQL designer to model the "Northwind" sample database:

We'll revisit our data model in Step 5 of this tutorial below when we add some business validation rules to it.  But to begin with we'll just use the above data model as-is to build our UI.

Step 2: Creating a Basic Product Listing

We'll start our UI by creating an ASP.NET page with a <asp:gridview> control on it and use some CSS to style it:

We could write code to programmatically bind our data model to the GridView (like I did in Part 3 of this series), or alternatively I could use the new <asp:linqdatasource> control to bind the GridView to our data model. 

VS 2008 includes build-in designer support to make it easy to connect up our GridView (or any other ASP.NET server control) to LINQ data.  To bind our grid above to the data model we created earlier, we can switch into design-view, select the GridView, and then select the "New Data Source..." option within the "Choose Data Source:" drop-down:

This will bring up a dialog box that lists the available datasource options to create.  Select the new "LINQ" option in the dialog box and name the resulting <asp:linqdatasource> control you want to create:

The <asp:linqdatasource> designer will then display the available LINQ to SQL DataContext classes that your application can use (including those in class libraries that you are referencing):

We'll want to select the data model we created with the LINQ to SQL designer earlier.  We'll then want to select the table within our data model that we want to be the primary entity for the <asp:linqdatasource> to bind against.  For this scenario we'll want to select the "Products" entity class we built.  We'll also want to select the "Advanced" button and enable updates and deletes for the datasource:

When we click the "Finish" button above, VS 2008 will declare a <asp:linqdatasource> within our .aspx page, and update the <asp:gridview> to point to it (via its DataSourceID property).  It will also automatically provide column declarations in the Grid based on the schema of the Product entity we choose to bind against:

We can then pull up the "smart task" context UI of the GridView and indicate that we want to enable paging, sorting, editing and deleting on it:

We can then press F5 to run our application, and have a product listing page with full paging and sorting support (note the paging indexes at the bottom of the grid below):

We can also select the "edit" or "delete" button on each row to update the data:

If we flip into source view on the page, we'll see that the markup of the page contains the content below.  The <asp:linqdatasource> control points at the LINQ to SQL DataContext we created earlier, as well as the entity table we want to bind against.  The GridView then points at the <asp:linqdatasource> control (via its DataSourceID) and indicates which columns should be included in the grid, what their header text should be, as well as what sort expression to use when the column header is selected. 

Now that we have the basics of our web UI working against our LINQ to SQL data-model, we can go ahead and further customize the UI and behavior.

Step 3: Cleaning up our Columns

Our GridView above has a lot of columns defined within it, and two of the column values (the SupplierID and the CategoryID) are currently foreign-key numbers -- which certainly isn't the ideal way to represent them to an end-user. 

Removing Unnecessary Columns 

We can start cleaning up our UI by deleting a few of the columns we don't need.  I can do this in source mode (simply nuke the <asp:boundfield> declarations) or in designer mode (just click on the column in the designer and choose the "Remove" task).  For example, we could remove the "QuantityPerUnit" column below and re-run our application to get this slightly cleaner UI:

If you have used the <asp:ObjectDataSource> control before and explicitly passed update parameters to update methods (the default when using DataSet based TableAdapters) one of the things you know can be painful is that you have to change the method signatures of your TableAdapter's update methods when the parameters based by your UI are modified.  For example: if we deleted a column in our grid (like above), we'd end up having to modify our TableAdapter to support update methods without that parameter.

One of the really nice things about the <asp:LinqDataSource> control is that you do not need to-do these types of changes.  Simply delete (or add) a column from your UI and re-run the application - no other changes are required.  This makes changing web UI built using the <asp:LinqDataSource> much easier, and enables much faster scenarios iterations within an application.

Cleaning up the SupplierID and CategoryID Columns

Currently we are displaying the foreign-key integer values in our GridView for the Supplier and Category of each Product: 

While accurate from a data model perspective, it isn't very end-user friendly.  What I really want to-do is to display the CategoryName and SupplierName instead, and provide a drop-downlist while in Edit mode to enable end-users to easily associate the SupplierID and CategoryID values.

I can change the GridView to display the Supplier Name and Category Name instead of the ID's by replacing the default <asp:BoundField> in our GridView with an <asp:TemplateField>.  Within this TemplateField I can add any content I want to customize the look of the column. 

In the source code below I'm going to take advantage of the fact that each Product class in the LINQ to SQL data model we created has a Supplier and Category property on it. What this means is that I can easily databind their Supplier.CompanyName and Category.CategoryName sub-properties within our Grid:

 

And now when I run the application I get the human readable Category and Supplier name values instead:

To get drop-down list UI for the Supplier and Category columns while in Edit-Mode in the Grid, I will first add two additional <asp:LinqDataSource> controls to my page.  I will configure these to bind against the Categories and Suppliers within the LINQ to SQL data model we created earlier:

I can then go back to the <asp:TemplateField> columns we added to our GridView earlier and customize their edit appearance (by specifying an EditItemTemplate).  We'll customize each column to have a dropdownlist control when in edit mode, where the available values in the dropdownlists are pulled from the categories and suppliers datasource controls above, and where we two-way databind the selected value to the Product's SupplierID and CategoryID foreign keys:

And now when end-users click edit in the GridView, they are presented a drop-down list of all valid Supplier's to associate the product with:

And when they hit save the Product is updated appropriately (the GridView will use the DropDownList's currently selected value to bind the SupplierID).

Step 4: Filtering our Product Listing

Rather than show all products within the database, we can update our UI to include a dropdownlist that allows the user to filter the products by a particular category. 

Because we already added a <asp:LinqDataSource> control to the page earlier that references our Categories within our LINQ to SQL data model, all I need to-do to create a drop-downlist control at the top of the page that binds against this.  For example:

When I run the page I'll now get a filter dropdownlist of all categories at the top of the page:

My last step is to configure the GridView to only show those Products in the category the end-user selects from the dropdownlist.  The easiest way to-do this is by selecting the "Configure DataSource" option in the GridView smart task:

This will bring me back to the <asp:LinqDataSource> control's design-time UI that we used at the very beginning of this tutorial.  I can select the "Where" button within this to add a binding filter to the datasource control.  I can add any number of filter expressions, and declaratively pull the values to filter by from a variety of places (for example: from the querystring, from form-values, from other controls on the page, etc):

Above I'm going to choose to filter by the Products by their CategoryID value, and then retrieve this CategoryID from the DropDownList control we just created on our page:

When we hit finish, the <asp:linqdatasource> control in our page will have been updated to reflect this filter clause like so:

And when we now run the page the end-user will now be able to select from the available Categories in the filter drop-downlist and page, sort, edit and delete just the products in that category:

The <asp:LinqDataSource> control will automatically apply the appropriate LINQ filter expression when working against our LINQ to SQL data model classes to ensure that only the required data is retrieved from the database (for example: in the Grid above only the 3 rows of Product data from the second page of Confection products will be retrieved from the database).

You can optionally handle the Selecting event on the <asp:LinqDataSource> if you want to write a custom LINQ expression in code to completely customize the query instead.

Step 5: Adding Business Validation Rules

As I discussed in Part 4 of this LINQ to SQL series, when we define LINQ to SQL data models we will automatically have a default set of schema based validation constraints added to our data model classes.  This means that if I try and enter a null value for a required column, try and assign a string to an integer, or assign a foreign-key value to a row that doesn't exist, our LINQ to SQL data model will raise an error and ensure that our database integrity is maintained.

Basic schema validation is only a first step, though, and is rarely enough for most real-world applications.  Typically we'll want/need to add additional business rules and application-level validation to our data model classes.  Thankfully LINQ to SQL makes adding these types of business validation rules easy (for details on the various validation approaches available, please read Part 4 of my LINQ to SQL series).

Example Business Validation Rule Scenario

For example, let's consider a basic business logic rule we might want to enforce.  Specifically, we want to ensure that a user of our application can't discontinue a product while we still have units on backorder for it:

If a user tries to save the above row, we'll want to prevent this change from being persisted and throw an appropriate error telling the user how to fix it.

Adding a Data Model Validation Rule

The wrong place to add this type of business validation rule is in the UI layer of our application.  Adding it in the UI layer of our application will mean that the rule will be specific to only that one place, and will not be automatically enforced when we add another page to our application that also updates Products.  Distributing business rules/logic in our UI layer will also make life extremely painful as our application grows in size - since changes/updates to our business will necessitate making code changes all over the place.

The right place to specify this type of business logic validation is instead in our LINQ to SQL data model classes that we defined earlier.  As I discussed in Part 4 of this series, all classes generated by the LINQ to SQL designer are defined as "partial" classes - which means that we can easily add additional methods/events/properties to them.  The LINQ to SQL data model classes automatically call validation methods that we can implement to enforce custom validation logic within them.

For example, I could add a partial Product class to my project that implements the OnValidate() partial method that LINQ to SQL calls prior to persisting a Product entity.  Within this OnValidate() method I could add the following business rule to enforce that products can't have a Reorder Level if the product is discontinued:

Once I add the above class into my LINQ to SQL project, the above business rule will be enforced anytime anyone uses my data model to try and modify the database.  This is true for both updating existing Products, as well as adding new Products into the database.

Because the <asp:LinqDataSource> that we defined in our pages above works against our LINQ to SQL data model classes, all of its update/insert/delete logic will now have to pass the above validation check prior to the change being persisted.  We do not need to-do anything to our UI tier in order for this validation to occur - it will automatically be applied anywhere and everywhere our LINQ to SQL data model is used.

Adding Nice Error Handling in our UI Tier

By default if a user now uses our GridView UI to enter a non-valid UnitsOnOrder/Discontinued combination, our LINQ to SQL data model classes will raise an exception.  The <asp:LinqDataSource> will in turn catch this error and provides an event that users can use to handle it.  If no one handles the event then the GridView (or other) control bound to the <asp:LinqDataSource> will catch the error and provide an event for users to handle it.  If no one handles the error there then it will be passed up to the Page to handle, and if not there to the global Application_Error() event handler in the Global.asax file.  Developers can choose any place along this path to insert appropriate error handling logic to provide the right end-user experience.

For the application we defined above, probably the best place to handle any update errors is by handling the RowUpdated event on our GridView.  This event will get fired every time an update is attempted on our datasource, and we can access the exception error details if the update event fails.  We can add the below code to check if an error occurs, and if so display an appropriate error message to the end-user:

Notice above how we have not added any validation specific logic into our UI.  Instead, I am retrieving the validation error message string we raised in our business logic and am using it to display an appropriate message to the end-user (I am then displaying a more generic error message in the event of other failures). 

Notice how I'm also indicating above that I want the GridView to stay in Edit mode when an error occurs - that way the user can avoid losing their changes, and can modify the values they entered and click "update" again to try and save them.  We can then add a <asp:literal> control with the "ErrorMessage" ID anywhere we want on our page to control where where we want the error message to be displayed:

And now when we try and update the Product with an invalid value combination we'll see an error message indicating how to fix it:

The nice thing about using this approach is that I can now add or change my data model's business rules and not have to modify any of my UI tier's code to have them pick up and honor the changes.  The validation rules, and corresponding error messages, can be written and centralized in one place in my data model and automatically applied everywhere.

Summary

The <asp:LinqDataSource> control provides an easy way to bind any ASP.NET UI control to a LINQ to SQL data model.  It enables UI controls to both retrieve data from a LINQ to SQL data model, as well as cleanly apply updates/inserts/deletes to it. 

In our application above we used the LINQ to SQL ORM designer to create a clean, object oriented data model.  We then added three ASP.NET UI controls to our page (a GridView, a DropDownList, and a ErrorMessage Literal), and added three <asp:LinqDataSource> controls to bind Product, Category, and Supplier data from it:

We then wrote 5 lines of business validation logic in our data model, and 11 lines of UI error handling logic. 

The end result is a simple web application with custom UI that allows users to dynamically filter product data by category, efficiently sort and page over the product results, inline-edit the product data to save updates (providing our business rules pass), and delete products from the system (also providing our business rules allow it).

In future posts in this series I'll cover more LINQ to SQL scenarios including optimistic concurrency, lazy and eager loading, table mapping inheritance, and custom SQL/SPROC usage.

Next week I also plan to start a new series of blog posts that cover the new <asp:ListView> control - which is a new control that will ship with the ASP.NET release in .NET 3.5.  It provides total control over the markup generated for data scenarios (no tables, no spans, no inline styles...), while also delivering built-in support for paging, sorting, editing, and insertion scenarios.  For example, we could optionally use it to replace the default Grid layout look of our application above with a completely custom look and feel.  Best of all, I could replace it within the above page in my application and not have to change my Data Model, the <asp:linqdatasource> declaration, or my code-behind UI error handling logic at all.

Hope this helps,

Scott

posted @ 2007-07-25 15:45 拾荒时代 阅读(277) 评论(0) 编辑

VS 2008 JavaScript Debugging


VS 2008 JavaScript Debugging

A few weeks ago I blogged about the new JavaScript Intellisense support in VS 2008.

One of the other JavaScript features that I'm sure will be popular in VS 2008 is the much-improved support for JavaScript debugging.  This is enabled in both the free Visual Web Developer 2008 Express edition as well as in Visual Studio, and makes using JavaScript and building AJAX applications significantly easier.

Setting JavaScript breakpoints in ASP.NET pages

One of the annoying things with VS 2005 is that you have to first run your ASP.NET pages before you can set JavaScript breakpoints in them in the debugger.  

VS 2008 makes this much better by adding new support that allows you to set client-side JavaScript breakpoints directly within your server-side .aspx and .master source files:

When you set a breakpoint in your .aspx page like above, VS 2008 will automatically map the breakpoint location to the dynamically generated client HTML that runs in the browser when the page is later executed:

If you add/remove/update the breakpoint locations in the running HTML document, VS 2008 is also now smart enough to perform the reverse mapping and update the breakpoint in the original .aspx or .master source file on the server.  This makes it much easier to get into a nice edit/debug/edit/debug flow as you are iterating on your applications.

Best of all, you can now set both client-side JavaScript breakpoints and VB/C# server-side breakpoints at the same time (even in the same page) and use a single debugger to step through both the server-side and client-side code in a single debug session (which is extremely useful for any AJAX heavy application).

Any JavaScript breakpoints you set will also now by default be saved by VS 2008 when you close the project/solution.  When you open up the project again, the previous locations you set the breakpoints on will still have them enabled. 

Script Document Navigation within the Solution Explorer

Often the JavaScript that is sent down to a browser client is dynamically generated on the server (for example: with scripts that are stored as resources within compiled server controls - like ASP.NET AJAX UpdatePanels and control extenders).  In scenarios such as these, you want to be able to easily see all JavaScript URLs being loaded from a page, as well as step into the within the debugger.

VS 2008 makes it much easier to-do this by integrating the running Script Document feature (that in VS 2005 was a separate tool-pane window) into the VS 2008 solution explorer view when you are debugging a web application. 

Specifically, when you are using VS to run and debug a page, VS 2008 will now list all of the script URLs that the page you are debugging has loaded in the browser at the top of your VS solution explorer pane:

You can then double click on any of the URLs under the "Script Documents" node at the top to see the JavaScript file that was loaded in the page:

You can obviously then set breakpoints in the loaded JavaScript and debug everything. 

Much Richer Debug Watch/Locals and Visualizer Support

Easily opening and navigating JavaScript files in the debugger is nice - but the real meat of the improvements made with VS 2008 JavaScript debugging is in the much improved object execution and inspection support.  When you inspect a variable within the debugger using VS 2008, you'll find much more detailed object information is now available:

You can now browse runtime object methods:

You can now browse runtime object events:

And you now get much, much more detailed property and property type information of running objects.  Note below how I am traversing the div element's "parentElement" property to dynamically look up details about the element's parent HTML element and overall position within the HTML DOM:

You can obviously use the debugger property grid above to both lookup as well as set values.  You can also run code in the immediate window to retrieve and change JavaScript at runtime:

VS 2008 also provides support for pluggable debug visualizers that you can use with JavaScript debugging.  This enables developers to add extensions to the debugger that can work against running objects and provide richer visualization views of them.  For example, we could use the built-in "Text", "XML", or "HTML" visualizer to load a dialog to better inspect a value:

I suspect we might see a cool CodePlex project providing nice JSON and REST JavaScript visualizers soon. 

Summary

The above walkthrough hopefully provided a good overview of some of the new JavaScript debugging features coming soon.  There are many more JavaScript and AJAX features coming in VS 2008 and .NET 3.5 that I'll be covering in future blog posts. 

Note that because of the new VS 2008 multi-targeting support, you can use the JavaScript debugging features above with both ASP.NET applications built using .NET 3.5 (which also now has ASP.NET AJAX built-in), as well as with existing ASP.NET 2.0 applications (including ones that use the separate ASP.NET AJAX 1.0 download). This, combined with the new VS 2008 JavaScript intellisense support, provides a very compelling reason to start using VS 2008 - even if you are using it to only target .NET 2.0 applications.

Hope this helps,

Scott

P.S. To learn more about VS 2005 JavaScript Debugging, please read this blog post.  Dan Wahlin also recently posted a nice set of AJAX testing and debugging tools that I recommend checking out here.

Published Thursday, July 19, 2007 11:29 PM by ScottGu

posted @ 2007-07-25 15:38 拾荒时代 阅读(328) 评论(0) 编辑

How to Show Messenger-Like Popups Using AJAX

Introduction

You have already been using MSN Messenger to chat with friends, relatives, businesses, and much more. When someone signs in, a small popup window shows up on the right-bottom side of the screen, informing you that your friend X has just signed in. It is a nice way for MSN messenger to notify you about changes in the contacts online.

What about using the same technique on an ASP.NET page? In other words, suppose that you are monitoring a database table, where users place their orders online and you would like to be notified whenever a new request comes in to the database table.

In this article we will show you how to implement a messenger-like popup window whenever a new record is added to a database table. The popup will show on the bottom-right side of the screen on top of an ASP.NET page notifying you that a new record has been added. We will use ASP.NET 2.0 AJAX 1.0 Extensions and mainly the client library accompanies by the AJAX extensions.

Database Sample

In this article we will use a database table called MyInbox simulating your inbox on a mail server. This table contains EmailFrom, Body, and Date columns. These columns shall resemble an email that you have received in your inbox as an example.

Constructing the JavaScript

We will create a new AJAX enabled website, then open the Default.aspx page in the HTML source, and start adding our JavaScript that will handle showing and hiding the popup and querying the database to see if there are any new emails inserted.

First of all, we define a global variable.

Listing 1

var numberOfEmails_original= 0;

The numberOfEmails_original variable shall hold the number of emails present in the database table when the page first loads. We will see later on when and how this variable is used. Then, we attach an event handler for the Application’s Init method.

Listing 2

var app = Sys.Application;
            app.add_init(applicationInitHandler);
            function applicationInitHandler(sender, args) 
            {
              InboxService.GetLatestNumberOfEmails(OnCurrentNumberOfEmailsReady);
            }

What we are doing at the initialization of the Application is do a script service call to execute the GetLatestNumberOFEmails method located at the AJAX Service that we will discuss later on in the article. We are specifying the success callback function to run when a response is sent back from the server.

The idea in here is that, the first time the page loads, we get the current number of emails from the server and store it in the numberOfEmails_original as shown in the OnCurrentNumberOfEmailReady callback function below.

Listing 3

function OnCurrentNumberOfEmailsReady(result, userContext, methodName) 
            {
              numberOfEmails_original= result;
              // Start Checking
              StartChecking();
            }

As you can see, we set the result returned by the AJAX Service to the local variable numberOfEmails_original and then call a method named StartChecking().

Now that the original number of emails currently stored in the database is known, we can start checking from now on to any new email that is added to the database table.

The StartChecking method is as follows:

Listing 4

function StartChecking() 
            {
              InboxService.GetLatestNumberOfEmails(OnLastestNumberOfEmailsReady);
            }

The StartChecking function does nothing but a call to the same AJAX service method, InboxService.GetLastestNumberOfEmails. However, this time, we are passing in another success callback function which is the OnLatestNumberOfEmailsReady. The success callback function is shown below.

Listing 5

function OnLastestNumberOfEmailsReady(result, userContext, methodName)
            {
              var numberOfEmails_new = result;
              if (numberOfEmails_new > numberOfEmails_original)
              {
                ShowPopup();
                $get("modalBody").innerHTML = numberOfEmails_new - numberOfEmails_original;
                // Update the count here
                numberOfEmails_original = numberOfEmails_new;
              }
              // Start checking again
              window.setTimeout(StartChecking, 10000);
            }

The method starts by placing the result from the AJAX service into a local variable called numberOfEmails_new. This variable now holds the latest number of emails located in the database table.

Then the code checks if the number of emails currently stored in the database is greater than the number of emails originally the page has requested from the database. This means that new emails we have were inserted into the database since the last time the code queried the database.

If this is true, then a call to ShowPopup() function is done that is responsible for showing a popup the MSN Messenger way. Then the number of new emails is filled in the body of the popup window informing the user on the number of new emails received, and finally, the code sets the current number of emails in the database table to the numberOfEmails_original variable. This way the numberOfEmails_original variable is synchronized with the emails’ number in the database. Refreshing the value of this variable is very important for later checking on the client side.

The last statement in this method is a call for the StartChecking method encapsulated in a window.setTimeout function call. As you can see here, the same logic will run according to the milliseconds placed in the setTimeout function. So as long as the page is running, the checking will continue and every time a new email is added to the database table, a pop up window is shown on the screen to notify the user about the new emails that have been added.

The figure below shows the page when it first loads.

Figure 1: Page when first loaded

When a new record is inserted into the database while the above page is opened, you will notice a small messenger like pop up window is shown on the bottom-right side of the page as in Figure 2.


Figure 2

You can clearly see a popup window in the figure above that shows when the page checks the database table on the server and finds that the number of emails currently on the database is greater than the number of emails stored on the client side.

The last two functions to discuss are the ShowPopup and HidePopup functions that are used as utility methods to show and hide the popup window on the page.


Building the AJAX Service

In this final section of the article we will show you the simple AJAX Service that we have created that the client code will use to access the database and retrieve information about the number of records stored in the database.

Listing 6

[ScriptService]
            public class InboxService: System.Web.Services.WebService
            {
              [WebMethod]
              public int GetLatestNumberOfEmails()
              {
                int numberOfEmails = 0;
             
                using(SqlConnection conn = new SqlConnection
                  (WebConfigurationManager.ConnectionStrings[0].ConnectionString))
                {
                  using(SqlCommand cmd = new SqlCommand("GetLatestNumberOfEmails", conn))
                  {
                    cmd.CommandType = CommandType.StoredProcedure;
             
                    conn.Open();
                    numberOfEmails = (int)cmd.ExecuteScalar();
                  }
                }
             
                return numberOfEmails;
              }
            }

The first thing to notice is the ScriptService attribute located at top of the service name. This is very important if you want your Web service to be a script callable service. The above web service includes one Web method which is GetLatestNumberOfEmails that accesses the database and retrieves the total number of emails or records in the database.

Downloads

[Download Sample]

Conclusion

In this article we demonstrated how to build MSN Messenger-like popup windows to show up on the page when a new record is added to the database table. You can use the same technique in your Web application for any other goal. But the idea is the same, which is popping up windows on an ASP.NET Page due to an event that happened somewhere on the server.

Happy Ajaxified Dot Netting!!


 

Article Feedback

Title: *
Name: *
Url: ( Optional )
Comment: *
Please add 2 and 3 and type the answer here:

User Comments

Title: GOOG   
Name: Mr. Duc
Date: 7/25/2007 1:38:18 AM
Comment:
good, I love it, and I use example in my project. Thank you very much
Title: Re: Hiren   
Name: Bilal Haidar [MVP]
Date: 6/25/2007 1:50:19 AM
Comment:
Hiren,
You can visit my site here: http://bhaidar.net/cs/archive/2007/04/18/telerik-c-vb-net-converter.aspx

You can convert the code from C# to VB easily!

Hope this helps,
regards
Title: Very Nice Example   
Name: Hiren Jatakia
Date: 6/25/2007 1:41:04 AM
Comment:
Hello Bilal,
This is exactly i want, Nice article, but can i have VB version of this example, cause i require this in VB.net format not in c#, if u can send it to me, it would be very helpful for me......
Title: Nice codes   
Name: PAwan Kumar
Date: 6/24/2007 4:59:04 AM
Comment:
Nice tutorial ....keep it up
Title: database   
Name: somuvas
Date: 6/20/2007 1:55:22 AM
Comment:
this is db connections
Title: One Question Though   
Name: AzamSharp
Date: 6/14/2007 12:44:52 PM
Comment:
Hi Bilal,

Great article as usual. I have one question though. Is there any special reason that you used the UpdateProgress control?

Thanks,
Azam
Title: Very Very Nice Work   
Name: AzamSharp
Date: 6/13/2007 5:57:37 PM
Comment:
Hi Bilal,

Very very nice work. :)

Thanks,
Title: SW engineer   
Name: Vinh
Date: 6/13/2007 10:36:29 AM
Comment:
It is good article. Simple and easy to follow.
Title: Re:   
Name: Bilal Haidar [MVP]
Date: 6/13/2007 9:28:10 AM
Comment:
I never publish anything that it doesn't work!

Plus, there is a technical editing for this article! So I am sure it works!! Are you facing any problem?

Regards
Title: R u sure!   
Name: Vijay KArla
Date: 6/13/2007 4:28:25 AM
Comment:
Bilal, R u sure that it works?
Title: Great work   
Name: Sandeep Acharya
Date: 6/13/2007 3:56:32 AM
Comment:
Hi,

I have already gone thru some of your prev articles and this one also carries the excellence with no exception.

Keep providing us such nice stuffs.

Thanks

Sandeep Acharya
Title: Good Article   
Name: Joydip Kanjilal
Date: 6/13/2007 1:58:54 AM
Comment:
Hi Bilal,

This is a nice article. Keep this good work going.

Best,

Joydip
Title: It's Good   
Name: Anjali Kataria
Date: 6/12/2007 10:12:05 PM
Comment:
Feature that u explain with an examples Its good. Good Work keep Up GOOD LUCK
Title: Very Good Article   
Name: Haissam Abdul Malak
Date: 6/12/2007 1:22:24 AM
Comment:
Bilal, it was nice to see such an implementation. keep up the good work

Regards,

posted @ 2007-07-25 15:34 拾荒时代 阅读(379) 评论(0) 编辑