[转载]理解Javascript_09_Function与Object

mikel阅读(817)

[转载]理解Javascript_09_Function与Object – 笨蛋的座右铭 – 博客园.

在《理解JavaScript_08_函数对象》中讲解了很多函数对象的问题,同时也留下了许多疑问,今天让我们来解答部分问题。

注:理论过于深入,本人不改保证所有的理论都是正确的,但经过多方测试还未发现实际代码与理论冲突的问题。如有错误,望高人指点!

Function

首先回顾一下函数对象的概念,函数就是对象,代表函数的对象就是函数对象。所有的函数对象是被Function这个函数对象构造出来的。也就是 说,Function是最顶层的构造器。它构造了系统中所有的对象,包括用户自定义对象,系统内置对象,甚至包括它自已。这也表明Function具有自 举性(自已构造自己的能力)。这也间接决定了Function的[[call]]和[[constructor]]逻辑相同。

1 function Foo() {};
2 var foo = new Foo();
3 //Foo为foo的构造函数
4 alert(foo instanceof Foo); // true
5 //但是Function并不是foo的构造函数
6 alert(foo instanceof Function); // false
7 //Function为Foo的构造函数
8 alert(Foo instanceof Function);//true

上面的代码解释了foo和其构造函数Foo和Foo的构造函数Function的关系。(具体原理请参见Function与Object的内存关系图)

Object

对于Object它是最顶层的对象,所有的对象都将继承Object的原型,但是你也要明确的知道Object也是一个函数对象,所以说Object是被Function构造出来的。(关于Object并没有太多的理论)

Function与Object

这是本文的重点,非常重要!

01 alert(Function instanceof Function);//true
02 alert(Function instanceof Object);//true
03 alert(Object instanceof Function);//true
04
05 function Foo() {};
06 var foo = new Foo();
07 alert(foo instanceof Foo); // true
08 alert(foo instanceof Function); // false
09 alert(foo instanceof Object); // true
10 alert(Foo instanceof Function); // true
11 alert(Foo instanceof Object); // true

你能理解这些答案吗?那恭喜你,JavaScript语言的本质你已经理解了。

那么让我们来看一下Object与Function实际的关系吧:

在你看图之前,请先阅读函数对象与instanceof原理两篇文章,要不然内存图很难理解。

在这,我对内存图做一点说明:在函数对象一文中提到了函数对象的构造过程,在本文中提到Function为自举性的,所以说函数对象Foo的构造过 程和函数对象Function的构造过程是一样的。所以在图中给于高亮显示,我用’|’来分隔来表示它们的构造过程相同。根据instanceof的理 论,和内存图,可以将上面的语句都推导出正确的结果。在此我们不一一讲述了,读者自已体会吧。

如果你不能理解这张复杂的内存图的话,可以看下面的说明图来帮助理解:

注:代码的实际执行流程并不完全像这张图上描述的那样,也就是说这张图是有问题的(可以说是错误的),它无法解释为什么Function instanceof Function 为true。 但是它易于理解Function与Object的关系。

[转载]理解Javascript_07_理解instanceof实现原理

mikel阅读(912)

[转载]理解Javascript_07_理解instanceof实现原理 – 笨蛋的座右铭 – 博客园.

在《Javascript类型检测》一文中讲到了用instanceof来用做检测类型,让我们来回顾一下:

那么instanceof的这种行为到底是如何实现的呢,现在让我们揭开instanceof背后的迷雾。

instanceof原理

照惯例,我们先来看一段代码:

01 function Cat(){}
02 Cat.prototype = {}
03
04 function Dog(){}
05 Dog.prototype ={}
06
07 var dog1 = new Dog();
08 alert(dog1 instanceof Dog);//true
09 alert(dog1 instanceof Object);//true
10
11 Dog.prototype = Cat.prototype;
12 alert(dog1 instanceof Dog);//false
13 alert(dog1 instanceof Cat);//false
14 alert(dog1 instanceof Object);//true;
15
16 var  dog2= new Dog();
17 alert(dog2 instanceof Dog);//true
18 alert(dog2 instanceof Cat);//true
19 alert(dog2 instanceof Object);//true
20
21 Dog.prototype = null;
22 var dog3 = new Dog();
23 alert(dog3 instanceof Cat);//false
24 alert(dog3 instanceof Object);//true
25 alert(dog3 instanceof Dog);//error

让我们画一张内存图来分析一下:

内存图比较复杂,解释一下:

程序本身是一个动态的概念,随着程序的执行,Dog.prototype会不断的改变。但是为了方便,我只画了一张图来表达这三次 prototype引用的改变。在堆中,右边是函数对象的内存表示,中间的是函数对象的prototype属性的指向,左边的是函数对象创建的对象实例。 其中函数对象指向prototype属性的指针上写了dog1,dog2,dog3分别对应Dog.prototype的三次引用改变。它们和栈中的 dog1,dog2,dog3也有对应的关系。(注:关于函数对象将在后续博文中讲解)

来有一点要注意,就是dog3中函数对象的prototype属性为null,则函数对象实例dog3的内部[[prototype]]属性将指向Object.prototype,这一点在《理解Javascript_06_理解对象的创建过程》已经讲解过了。

结论

根据代码运行结果和内存结构,推导出结论:

instanceof 检测一个对象A是不是另一个对象B的实例的原理是:查看对象B的prototype指向的对象是否在对象A的[[prototype]]链上。如果在,则 返回true,如果不在则返回false。不过有一个特殊的情况,当对象B的prototype为null将会报错(类似于空指针异常)。

这里推荐一篇文章,来自于岁月如歌,也是关于instanceof原理的,角度不同,但有异曲同工之妙。

1 http://lifesinger.org/blog/2009/09/instanceof-mechanism/

[转载]有关网站UI实现的几种方式的讨论

mikel阅读(1125)

[转载]有关网站UI实现的几种方式的讨论 – LoveCherry – 博客园.

抛砖引玉,提出一些知道的做法,欢迎大家提出更多做法。

对于网站来说,UI最终的形式无非是(X)HTML + 脚本 + 样式,现在的问题是怎么样生成这些前端的元素,在以下几个方面达到平衡:

(假设有开发和前端两种角色,前端负责表现逻辑和表现,而开发负责业务逻辑和业务数据)

1) 开发人员的工作量,工作难度

2) 前端开发人员(后面省略为前端)的工作量,工作难度

3) 产品(假设前端属于产品部)对UI的改动需求能否快速落实(能否只依靠前端实现)

4) 服务端的压力(客户端的性能问题暂时不考虑)

(怎么发现自从翻译了《微软应用架构指南》之后,写什么都是翻译的口气了)

第一种方式:XML + XSLT

数据源是XML,由开发人员提供,XSL可以一开始由开发人员写,以后由前端参与开发和维护。

T的过程可以在服务端进行,优点是搜索引擎友好,缺点是服务端压力大。

T的过程也可以在客户端进行,和服务端进行的优缺点互反。

这种方式比较适用访问量大(特别是客户端进行T)、交互简单的系统,比如论坛,因为服务端只需要提供数据源,而XSL则是静态资源可以在客户端缓存。

这种方式的优点是,如果前端直接维护XSL,那么在开发不介入的情况下可以直接对页面布局等进行调整,并且可以做到最好的性能。

而缺点则是,学习成本比较大,如果在客户端进行转换那么搜索引擎支持会不好,而且XSL相对比较难以维护,实现复杂逻辑成本比较大。
第二种方式:ASP.NET Webform

最常见的方式,基于控件,由控件生成HTML,开发也可以直接操作服务端控件。这是一种开发人员主导的方式。

这是一种普适的方式,什么应用都可以支持。缺点是不太利于实现UI快速改动,前端很难参与aspx的维护,因为很多UI都是由控件进行,开发人员很可能在后端操作控件进行一些UI的修改。

第三种方式:纯粹的JavaScript + 服务端数据源

所有和呈现相关的逻辑,都由JavaScript来写(可以依赖JQuery,jtemplate等组件),以AJAX方式从服务端获取数据进行数据的填充和一些业务逻辑的实现。

这是一种前端主导的方式,会写大量的脚本来实现逻辑,需要的数据从服务端获取。

这种方式比较适合前端互动比较丰富的应用,比如网页游戏。

优点是,前端对页面的布局、行为有很大的自主权,并且服务端的压力也比较小。

缺点是,需要写大量的脚本代码,难度大并且容易出错,并且容易出现安全问题。

第四种方式:模板引擎

模板引擎通过基于HTML的模板加上各种预定义的占位符来实现数据的动态填充。在保证了UI灵活性的同时也保证了非常高的性能。

这种方式对于需要有多界面的新闻系统、博客系统,甚至每一个版块布局都不同的论坛系统来说很适用。

虽然足够灵活,但是前端和开发的配合还是双向的,也就是前端还是需要知道开发提供的数据结构。

并且,对于交互比较复杂的应用来说,可能需要用模板引擎预定义的脚本来写很多逻辑,造成难以维护。

第五种方式:ASP.NET MVC

这同样是一种普适的方式,只不过更适用于面向互联网网站,而不是面向局域网的内部应用。

虽然MVC已经在UI和UI逻辑方面实现了很好的分离,但是我觉得还是很难在开发没有介入的情况下直接对页面的布局等进行调整。

第六种方式:在服务端为HTML的适当位置动态注入数据

这是一种比较新颖的方式,在服务端加载HTML作为模板文件,然后写代码修改HTML中的dom元素,为元素填充数据。

比如一个a.html配合a.shtml,a.shtml(httphandler)加载a.html然后解析HTML文档,从数据库加在数据填充到HTML中,输出这个HTML。

前端提供的HTML文件可以直接使用,不需要加任何模板标签,不需要加任何控件,所有数据由代码填充进去。

可以像JQuery一样支持各种方式来搜索数据的填充路径,也可以把一段html作为模板,循环复制成一个列表页面。

优点是,前端维护HTML/脚本/样式,开发人员写代码生成数据,填充数据,彻底的分离。

缺点是,前端不能改变一些涉及到路径的元素(比如我们通过className来定位元素,前端改变了className就不行),还有性能可能会差一点。

第七种方式:在服务端为HTML动态载入数据,在客户端注入数据

还是以HTML作为模板文件,只不过这个数据组装的过程在客户端进行,相比第六种方式有更好的性能。

也就是服务端不用解析HTML文档,直接为HTML文档中加上一个JSON数据片段,这些数据是这个页面需要的所有数据。

然后,在服务端使用ScriptSharp等框架编译时生成填充数据到HTML的脚本,这个填充过程由客户端执行。

代码还是像第六种方式一样写,但是这段代码会完成两个工作,一个是把部分代码生成脚本文件,第二是把部分代码生成json数据写到页面上。

好像还没看到过有现成的框架是这么干的,难道这种方式不太实用?

其实演变一下的话,也可以是直接写脚本,不用ScriptSharp来生成,但是在服务端写的很大的一个好处是可以直接利用强类型的实体。

想象一下这样的伪代码:Document.FindElement(“path”).Fill(product.Take(10), product => product.Name);

这样,product这个List的前10项就会以json输出在页面上,而定位元素以及赋值的代码也会以jQuery/JavaScript代码输出在页面上。

优缺点和第六种方式一致。

第八种方式:由服务端生成HTML

这是一种比较极端的方式,所有HTML由代码生成,可以拼字符串也可以利用SharpDom之类的框架。

适合UI随着业务逻辑变化非常大的流程系统,或者一些模板生成工具,不太适合业务系统。

欢迎讨论:

1) 您的网站是怎么样的业务并且采用哪种方式?

2) 还有什么更好的方式方便前端和开发职责的分离?

[转载]ASP.NET MVC3 让依赖注入来的更简单(新补充了Ninject示例)

mikel阅读(955)

[转载]ASP.NET MVC3 让依赖注入来的更简单(新补充了Ninject示例) – 马旭 – 博客园.

昨天,我写了一篇文章(参见:ASP.NET MVC 依赖注入),这种实现方式我个人一直感觉不太顺,在写出来与大家一起分享的同时,

也是想让大家提提自己的建议, 今天下载了微软发布的最新的 ASP.NET MVC3 Beta 版,同时也仔细阅读了它的 Release Notes,

让我感觉到惊喜的是,MVC3增加了对依赖注入的支持,增加了一个 IDependencyResolver 接口定义,真的是很不错,比起我原来的实现要顺畅很多,

还是老方法,上微软牛人们的博客逛一圈看看有没有已经写好的代码,有就拿来用之,没有就只能自己写了,结果让我很失望,也可能是我太笨,

我没有找到一个完整的示例,只有一些代码片断,于是,我将其整理了一翻,也有一点点个人的心得,拿出来,与大家分享一下,

如遇高人请不吝赐教,下面是代码片断。

1、实现 MVC3 Beta 中提供的依赖注入接口 IDependencyResolverMyDependencyResolver.cs 的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;

namespace Demo
{
public class MyDependencyResolver : IDependencyResolver
{
#region IDependencyResolver 成员

/// <summary>
/// 依赖注入容器
/// </summary>
private UnityContainer _unityContainer;

/// <summary>
/// 构造
/// </summary>
/// <param name=”aUnityContainer”>依赖注入容器</param>
public MyDependencyResolver( UnityContainer aUnityContainer )
{
_unityContainer
= aUnityContainer;
}

public object GetService( Type aServiceType )
{
try
{
return _unityContainer.Resolve( aServiceType );
}
catch
{
/// 按微软的要求,此方法,在没有解析到任何对象的情况下,必须返回 null,必须这么做!!!!
return null;
}
}

public IEnumerable<object> GetServices( Type aServiceType )
{
try
{
return _unityContainer.ResolveAll( aServiceType );
}
catch
{
/// 按微软的要求,此方法,在没有解析到任何对象的情况下,必须返回空集合,必须这么做!!!!
return new List<object>( );
}
}

#endregion
}

}

2、在 Global.asax.cs 中设置依赖注入解析器  DependencyResolver (这是一个全局静态类,也是 MVC3 Beta 新增的):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;

namespace Demo
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801

public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters( GlobalFilterCollection filters )
{
filters.Add( new HandleErrorAttribute( ) );
}

public static void RegisterRoutes( RouteCollection routes )
{
routes.IgnoreRoute( {resource}.axd/{*pathInfo} );

routes.MapRoute(
Default, // Route name
{controller}/{action}/{id}, // URL with parameters
new { controller = Home, action = Index, id = UrlParameter.Optional }
);

}

protected void Application_Start( )
{
AreaRegistration.RegisterAllAreas( );

RegisterGlobalFilters( GlobalFilters.Filters );
RegisterRoutes( RouteTable.Routes );
//设置依赖注入
RegisterDependency( );
}

private static UnityContainer _Container;
public static UnityContainer Container
{
get
{
if ( _Container == null )
{
_Container = new UnityContainer( );
}
return _Container;
}
}

protected void RegisterDependency( )
{
Container.RegisterType<ITest, Test>( );
DependencyResolver.SetResolver( new MyDependencyResolver( Container ) );
}
}
}

3、Controller的代码,HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;

namespace Demo.Controllers
{
public class HomeController : Controller
{
[Dependency]
public ITest Test { get; set; }

public ActionResult Index( )
{
ViewModel.Message = Test.GetString( );

return View( );
}

public ActionResult About( )
{
return View( );
}
}
}

4、ITest.cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo
{
public interface ITest
{
string GetString( );
}
}

5、Test.cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Demo
{
public class Test:ITest
{
#region ITest 成员

public string GetString( )
{
return Run demo!;
}

#endregion
}
}

***** 注意,这篇文章只适用于 ASP.NET MVC3 Beta 版,将来正式版出来了,未必采用这种方式来实现,毕竟对于依赖注入这块,

从 MVC1 -> MVC3 Preview1 -> MVC3 Beta 一直都在变化,微软牛人(Brad Wilson)在自己的博客中也多次提到:

Disclaimer

This blog post talks about ASP.NET MVC 3 Beta, which is a pre-release version. Specific technical details may change before the final release of MVC 3.

This release is designed to elicit feedback on features with enough time to make meaningful changes before MVC 3 ships,

so please comment on this blog post or contact me if you have comments.

(参见原文:http://bradwilson.typepad.com/blog/2010/10/service-location-pt5-idependencyresolver.html

在下 e 文太差,我就不丢人了,e 文好的自己看吧。

这里是采用Unity依赖注入框架的完整示例:下载(环境:VS2010 + MVC3 Beta + Unity)

这里是采用Ninject依赖注入框架的完整示例:下载(环境:VS2010 + MVC3 Beta + Ninject)

[转载]实现基于ASP.NET MVC快速开发平台

mikel阅读(854)

[转载]实现基于ASP.NET MVC快速开发平台 – 海纳百川 – 博客园.

最近一个月,自己利用业余时间开发一个基于ASP.NET MVC快速开发平台。现在勉强算个原型,但是感觉不是那么回事,把实现的过程写出来,欢迎大家拍砖。

开发思想:利用ASP.NET MVC的思想,实现自己的一套开发平台。

定位

1、基本无需程序员写代码,通过配置的方式实现项目。

2、在特定领域,提高ASP.NET MVC开发效率。

3、不同的程序员写出同样的代码。

4、提供一套可视化开发和代码生成的解决方案。

实现思路:

利用三个辅助开发工具生成Model、View、Controller的代码。

Model:三层架构代码生成器。

View:简易的表单设计器。我对表单的要求不是太高,通过几个封装好的控件组合成一个页面就行了。

Controller :自定义函数,可视化的编程。

通过三层架构代码生成器材生成Model。利用WPF或者SL实现一个可视化的表单设计器,通过反射Model,生成基本的操作页面,可以在设计器上拖拽和修改属性。使用WF4.0来处理业务逻辑,WF4.0的流程设计器非常强大,可以胜任复杂的业务逻辑处理。

步骤很简单:先生成Model,在根据Model反射出表单,然后在表单上关联和定义相应Action。

三层架构代码生成器:主要生成Model层的代码,用于数据的持久化。

表单设计器:设计View,和生成View代码,通过控件组合的方式生成UI,界面要求统一和简单。

函数设计器:实现可视化的编程。用于可视化的书写复杂的业务逻辑代码。

示例:

下面我一步一步使用这三个工具,开发一个数据展示的应用程序Demo。

第一步:新建一个自定义的MVC模板项目,这个是我自己封装的一个项目模板,包括一些常用的dll、js、css等等。

第二步:配置一级表单:

第三步:配置一级表单动作点函数

第四步:生成Action代码和保存WF代码

代码

public class HomeController : Controller { [HandleError] [HttpGet] public ActionResult Index() { IDictionary<string, object> inputs = new Dictionary<string, object>(); IDictionary<string, object> results = WorkflowInvoker.Invoke(new IndexWF(), inputs); return View(results["result"]); } }

WF代码:

第六步:生成View:Index.aspx代码

第七步:将生成好的东西放到第一步创建的项目中

运行:

定义展示的详情页面:

定义Action:

详情页面运行效果:

总结:文本是对我用一个月业余时间走火入魔般的写的一个开发工具的总结。虽然没有达到我想要的结果,但是还是对MVC有了更进一步的了解。如果你也有这方面的想法和思考,欢迎加入QQ群96378091讨论,或者直接在我blog给我留言,谢谢。

代码下载:http://files.cnblogs.com/zhuqil/MvcCRUD.rar

作者:朱祁林
出处:http://zhuqil.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

[转载]ASP.NET中找不到类型或命名空间名称SQLDMO解决方案

mikel阅读(864)

[转载]ASP.NET中找不到类型或命名空间名称SQLDMO解决方案_甜甜_新浪博客.

SQLDMO(SQL Distributed Management Objects,SQL分布式管理对象)封装了Microsoft SQL Server数据库中的对象。SQLDMO是Microsoft SQL Server中企业管理器所使用的应用程序接口,所以它可以执行很多功能,其中当然也包括对数据库的备份和恢复。

SQLDMO由Microsoft SQL Server自带的SQLDMO.dll提供,由于SQLDMO.dll是一个COM对象,所以大家在用之前必须在.NET项目中添加对它的引用,其路径是“C:\Program Files\Microsoft SQL Server\80\Tools\Binn”。


在.NET项目中添加 SQLDMO引用的步骤是:
1.在.NET项目的解决方案中,单击右键,选择“添加引用”,将弹出“添加引用”对话框,如图所示:
ASP.NET中找不到类型或命名空间名称SQLDMO解决方案
2.在“浏览”选项卡中,找到SQLDMO.DLL的存放路径,然后单击“确定”即可。

[转载]ASP.NET MVC3 让依赖注入来的更简单

mikel阅读(1036)

[转载]ASP.NET MVC3 让依赖注入来的更简单 – 马旭 – 博客园.

昨天,我写了一篇文章(参见:ASP.NET MVC 依赖注入),这种实现方式我个人一直感觉不太顺,在写出来与大家一起分享的同时,

也是想让大家提提自己的建议, 今天下载了微软发布的最新的 ASP.NET MVC3 Beta 版,同时也仔细阅读了它的 Release Notes,

让我感觉到惊喜的是,MVC3增加了对依赖注入的支持,增加了一个 IDependencyResolver 接口定义,真的是很不错,比起我原来的实现要顺畅很多,

还是老方法,上微软牛人们的博客逛一圈看看有没有已经写好的代码,有就拿来用之,没有就只能自己写了,结果让我很失望,也可能是我太笨,

我没有找到一个完整的示例,只有一些代码片断,于是,我将其整理了一翻,也有一点点个人的心得,拿出来,与大家分享一下,

如遇高人请不吝赐教,下面是代码片断。

1、实现 MVC3 Beta 中提供的依赖注入接口 IDependencyResolverMyDependencyResolver.cs 的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;

namespace Demo
{
public class MyDependencyResolver : IDependencyResolver
{
#region IDependencyResolver 成员

/// <summary>
/// 依赖注入容器
/// </summary>
private UnityContainer _unityContainer;

/// <summary>
/// 构造
/// </summary>
/// <param name=”aUnityContainer”>依赖注入容器</param>
public MyDependencyResolver( UnityContainer aUnityContainer )
{
_unityContainer
= aUnityContainer;
}

public object GetService( Type aServiceType )
{
try
{
return _unityContainer.Resolve( aServiceType );
}
catch
{
/// 按微软的要求,此方法,在没有解析到任何对象的情况下,必须返回 null,必须这么做!!!!
return null;
}
}

public IEnumerable<object> GetServices( Type aServiceType )
{
try
{
return _unityContainer.ResolveAll( aServiceType );
}
catch
{
/// 按微软的要求,此方法,在没有解析到任何对象的情况下,必须返回空集合,必须这么做!!!!
return new List<object>( );
}
}

#endregion
}

}

2、在 Global.asax.cs 中设置依赖注入解析器  DependencyResolver (这是一个全局静态类,也是 MVC3 Beta 新增的):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;

namespace Demo
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801

public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters( GlobalFilterCollection filters )
{
filters.Add( new HandleErrorAttribute( ) );
}

public static void RegisterRoutes( RouteCollection routes )
{
routes.IgnoreRoute( {resource}.axd/{*pathInfo} );

routes.MapRoute(
Default, // Route name
{controller}/{action}/{id}, // URL with parameters
new { controller = Home, action = Index, id = UrlParameter.Optional }
);

}

protected void Application_Start( )
{
AreaRegistration.RegisterAllAreas( );

RegisterGlobalFilters( GlobalFilters.Filters );
RegisterRoutes( RouteTable.Routes );
//设置依赖注入
RegisterDependency( );
}

private static UnityContainer _Container;
public static UnityContainer Container
{
get
{
if ( _Container == null )
{
_Container = new UnityContainer( );
}
return _Container;
}
}

protected void RegisterDependency( )
{
Container.RegisterType<ITest, Test>( );
DependencyResolver.SetResolver( new MyDependencyResolver( Container ) );
}
}
}

3、Controller的代码,HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;

namespace Demo.Controllers
{
public class HomeController : Controller
{
[Dependency]
public ITest Test { get; set; }

public ActionResult Index( )
{
ViewModel.Message = Test.GetString( );

return View( );
}

public ActionResult About( )
{
return View( );
}
}
}

4、ITest.cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo
{
public interface ITest
{
string GetString( );
}
}

5、Test.cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Demo
{
public class Test:ITest
{
#region ITest 成员

public string GetString( )
{
return Run demo!;
}

#endregion
}
}

***** 注意,这篇文章只适用于 ASP.NET MVC3 Beta 版,将来正式版出来了,未必采用这种方式来实现,毕竟对于依赖注入这块,

从 MVC1 -> MVC3 Preview1 -> MVC3 Beta 一直都在变化,微软牛人(Brad Wilson)在自己的博客中也多次提到:

Disclaimer

This blog post talks about ASP.NET MVC 3 Beta, which is a pre-release version. Specific technical details may change before the final release of MVC 3.

This release is designed to elicit feedback on features with enough time to make meaningful changes before MVC 3 ships,

so please comment on this blog post or contact me if you have comments.

(参见原文:http://bradwilson.typepad.com/blog/2010/10/service-location-pt5-idependencyresolver.html

在下 e 文太差,我就不丢人了,e 文好的自己看吧。

这里是完整的示例:下载(环境:VS2010 + MVC3 Beta + Unity)

[转载]Use External Interface of Flash 8 in Python and C# Applications Open Source Flash

mikel阅读(1235)

[转载]Use External Interface of Flash 8 in Python and C# Applications Open Source Flash.

A discussion about the External Interface of Flash8 has been post in this thread. And here we demonstrate how to use External Interface of Flash8 in Python and C# applications, we talk about how to serialize/deserialize the data passed through External Interface from/to Python and C#, and how to wrap these things up.

Data Structure in Xml

Data exchange through the External Interface is in a Xml-Rpc alike structure, so we need to write something serializer/deserializer to handle it, in this case, I use a separate class to handle this in Python and C#. For the detail, you should check the source code by yourself.

And the Wrapper

For easy use, We need a wrapper class around the Flash ax control, which help us registering callback functions for Flash side and calling Flash side functions. Check the source.

The Echo Sample

We supply a echo sample in both Python and C# files, which demonstrate the usage of the wrapper and the data conversion between Flash and the host.

JSCRIPT.NET:

/* 
* Jarrad Hope - May 2006 player.js 
* Enjoy! 
* jsc.exe /target:winexe player.js 
*/ 

import System; 
import System.Windows.Forms; 
import System.ComponentModel; 
import System.Drawing; 
import System.IO; 
import AxShockwaveFlashObjects; 

public class swfWindow extends Form {    
   private var mrSwf : AxShockwaveFlashObjects.AxShockwaveFlash; 

   function swfWindow() { 
   var startupSize = new System.Drawing.Size(800, 600); 
   // Swf Setup 
   this.mrSwf = new AxShockwaveFlash(); 
   this.mrSwf.BeginInit(); 
   this.mrSwf.Location = new Point(0,0); 
   this.mrSwf.Name = "mrSwf"; 
   this.mrSwf.TabIndex = 0; 
   this.Controls.Add(this.mrSwf); 
   this.mrSwf.Size = startupSize; 
   this.mrSwf.EndInit() 
   // Window Setup 
   this.mrSwf.Movie=Path.Combine(Directory.GetCurrentDirectory(),"test.swf"); 
   this.FormBorderStyle = 1; //Fixed Size 
   this.ClientSize = startupSize; 

   //ExternalInterface EXE->SWF 
   var recCall = this.mrSwf.CallFunction("<invoke name=\"callSwf\" returntype=\"xml\"><arguments><string>Ping!</string></arguments></invoke>"); 
   MessageBox.Show(recCall); 

   } 

} 

var window : swfWindow = new swfWindow(); 
window.ShowDialog();

Python:

class TestEIFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self,None,-1,
                          title='Test External Interface Between Python And Flash 8 - Echo',
                          size=(408,270))
        self.p=wx.Panel(self,-1)
        self.t=wx.TextCtrl(self.p,-1,pos=(200,0),size=(200,200),value='External Interface Echo',
                           style=wx.TE_MULTILINE)
        self.b=wx.Button(self.p,-1,pos=(200,205),size=(200,30),label='Press to Call Flash!')
        wx.EVT_BUTTON(self.b,self.b.GetId(),self.OnButton)
        self.asf=AxShockwaveFlashEx(self.p,-1,size=(200,240))
        self.asf.Scale='noScale'
        self.asf.Menu=False
        self.asf.RegisterCallback('echo',self.echo)
        self.asf.Movie=os.path.join(os.getcwd(),'eiecho.swf')
        return
    def echo(self,data):
        self.t.SetValue('Argument Received from Flash:\n\n')
        self.t.AppendText(str(data))
        return data
    def OnButton(self,evt):
        data={'a':705,
              'b':random.random(),
              'c':u'Hello World \u6587\u5b57 - Python',
              'd':[3,9,27],
              'e':None,
              'f':{'x':2.0,'y':4.5},
              'g':"",
              }
        self.t.SetValue('Argument Sended to Flash:\n\n')
        self.t.AppendText(str(data))
        data=self.asf.FlashSide.echo(data)
        self.t.AppendText('\n\nReturn Value from Flash:\n\n')
        self.t.AppendText(str(data))
        return

C#:

public class MainForm : System.Windows.Forms.Form
{
	private System.Windows.Forms.Button button1;
	private System.Windows.Forms.TextBox textBox1;
	private EIFlash.AxShockwaveFlashEx axShockwaveFlashEx1;
	public MainForm()
	{
		InitializeComponent();
		axShockwaveFlashEx1.Movie=System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(),"eiecho.swf");
		axShockwaveFlashEx1.RegisterCallback("echo",new DgEcho(Echo));
	}

	[STAThread]
	public static void Main(string[] args)
	{
		Application.Run(new MainForm());
	}

	#region Windows Forms Designer generated code
	private void InitializeComponent() {
		...
	}
	#endregion
	void InvokeFlashEcho(object sender, System.EventArgs e)
	{
		Hashtable echodata=new Hashtable();
		echodata.Add("a",100);
		System.Random r=new System.Random();
		echodata.Add("b",r.NextDouble());
		echodata.Add("c","Hello World 文字 - C#");
		echodata.Add("d",new int[]{2,4,8});
		echodata.Add("e",null);
		echodata.Add("f",false);
		Hashtable g=new Hashtable();
		g.Add("x",2.5);
		g.Add("y",7.525);
		echodata.Add("g",g);
		textBox1.Text="Argument Sended to Flash:\r\n\r\n";
		textBox1.Text+=Repr(echodata);
		object o=axShockwaveFlashEx1.CallFlashEx("echo",echodata);
		textBox1.Text+="\r\n\r\nReturn Value from Flash:\r\n\r\n";
		textBox1.Text+=Repr(o);
	}

	string Repr(object o)
	{
		if(o==null){
			return "<null>";
		}
		Type t=o.GetType();
		if(t==typeof(bool)){
			return "<bool:"+o.ToString()+">";
		}
		if(o is IList){
			IList a=(IList)o;
			string[] ss=new string[a.Count];
			for(int i=0;i<a.Count;i++){
				ss[i]=Repr(a[i]);
			}
			return "<"+t+"["+String.Join(", ",ss)+"]>";
		}
		if(o is IDictionary){
			IDictionary d=(IDictionary)o;
			string[] ss=new string[d.Count];
			int i=0;
			foreach(object k in d.Keys){
				ss[i++]=k.ToString()+": "+Repr(d[k]);
			}
			return "<"+t+"{"+String.Join(", ",ss)+"}>";
		}
		return o.ToString();
	}

	object Echo(object data)
	{
		textBox1.Text="Argument Received from Flash:\r\n\r\n"+Repr(data);
		return data;
	}
	delegate object DgEcho(object data);
}

Files Associated to this Tutorial

[转载]Moving a Subversion Repository to Another Server

mikel阅读(929)

[转载]Moving a Subversion Repository to Another Server.

Moving a subversion repository from one server to another, while still preserving all your version history may seam like a daunting task, but fortunately it’s not too difficult.

I recently had to move a subversion (svn) repository to another server. The repository was on a Windows server and had to be moved to a Linux server.

Step 1: Backup your old Repository

The first thing you need when moving from one server to another is a dump of your subversion repository. Hopefully you are already creating dump’s with a backup script, but if not here’s how you can create a subversion dump file:

svnadmin dump /path/to/repository > repo_name.svn_dump

The dump file contains all the revisions you have ever made to your svn repository, so it will probably be quite large (it even includes files you may have deleted in a previous revision).

Step 2: Create the new Repository

Now, simply transfer the dump file on to your new subversion server, and create an empty repository:

svnadmin create /path/to/repository

Step 3: Import your old repository into the new one

Next import your dump file:

svnadmin load /path/to/repository < repo_name.svn_dump

You may want to force subversion to use the same UUID for the new repository as the old repository. To do this add --force-uuid to your svnadmin load command. In my case I wanted to do this. If you have already loaded your repository, there is a way to set the UUID at a later date, check the docs.

That’s it, you now have a replica of your old repository on your new server.

FAQ’s

What if someone committed a new revision to the old server during installation?

You can easily import the new revision, by creating an incremental dump on the old server:

svnadmin dump --incremental -r 1234 /path/to/repository > rev1234.svn_dump

Now to import that revision on your new server:

svnadmin load /path/to/repository < rev1234.svn_dump

Can’t I just use a hotcopy to restore the repository?

It depends, hotcopies created with svnadmin hotcopy must be moved to a server with identical setup. You should have the same version of subversion installed on both servers, same operating system, etc.

Subversion dumps are designed to work with different versions of subversion, and are just more flexible. Hotcopies are handy to have, but I recommend creating both hotcopies and dumps as part of your backup plan.