JavaScript에서 관리 코드 호출

XAML 코드에 클라이언트 스크립트를 바인딩하려면

파일 위쪽에서 using 또는 Imports 문을 추가하여 System.Windows.Browser 네임스페이스를 가져옵니다.

// HtmlDocument requires using System.Windows.Browser;
HtmlDocument doc = HtmlPage.Document;
//Enable the HTML textbox on the page and say hello
doc.GetElementById("Text1").SetProperty("disabled", false);
doc.GetElementById("Text1").SetAttribute("value",   "This text set from managed code.");

(실버라이트에서 자바스크립트 호출)

aspx 페이지의 자바스크립트

<script>
    function TestBtn2(str) {
        slCtl.Content.mySLapp.Name = str;
    }
    function TestBtn() {

        alert(slCtl.Content.mySLapp.Name);
    }
</script>

실버라이트 cs 페이지

HtmlPage.Window.Invoke("Test", "");

또다른 방법

HtmlElement script = HtmlPage.Document.CreateElement("script");
script.SetAttribute("type", "text/javascript");
script.SetProperty("text", "alert('A')");
HtmlPage.Document.DocumentElement.AppendChild(script);

관리 코드에 대한 클라이언트 스크립트 액세스 테스트


image

실버라이트 페이지에 외부페이지와 스크립트 호출을 할수 있는 클래스를 만듭니다

using System.Windows.Browser;

namespace SilverlightApplicationCardTest
{
    public class MyScriptableManagedType
    {
        [ScriptableMember()]
        public string MyToUpper(string str) {
            return str.ToUpper();
        }

        [ScriptableMember()]
        public string Name { get; set; }
    }

}

 

 

App.xaml

페이지에서 외부에서 호출할 이름을 등록해줍니다

private void Application_Startup(object sender, StartupEventArgs e)
{
    this.RootVisual = new Page();

    //Set up some scriptable managed types for access from Javascript.
    MyScriptableManagedType smt = new MyScriptableManagedType();
    HtmlPage.RegisterScriptableObject("mySLapp", smt);

}

 

 

실버라이트가 포함된 페이지에서 처리부분

<script type="text/javascript" src="Silverlight.js"></script>
   <script type="text/javascript">
       var slCtl = null;

       function embedSilverlight(parentElement, pluginId, userContext) {
           var altHtml = pluginId == "sl1" ? null : "<!--not installed-->";
           return Silverlight.createObject("ClientBin/SilverlightApplicationCard.xap",
               parentElement, pluginId,
               {
                   width: "540", height: "340",
                   background: "white", alt: altHtml,
                   minRuntimeVersion: "2.0.30908.0", autoUpgrade: true
               },
               { onError: onSLError, onLoad: onSLLoad },
               "param1=value1,param2=value2", userContext);
       }

       function onSLLoad(plugIn, userContext, sender) {
           slCtl = sender.getHost();  //HTML 버젼

//// ASPX version
///slCtl = sender.get_element();


           alert(slCtl.Content.mySLapp.MyToUpper("Test String"));  //실제로 잘 불러와지는지 테스트

           window.status += plugIn.id + " loaded into " + userContext + ". ";
       }

       function onSLError(sender, args) {
           // Display error message.
       }
   </script>

 

</head>
<body style="height:100%;margin:0;">
    <form id="form1" runat="server" style="height:100%;">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <div  id="sl2Host">
             <script type="text/javascript">
                 embedSilverlight(sl2Host, "sl2", "row2"); //실버라이트 바인딩
                </script>
        </div>

<input type="button"  onclick="TestBtn()" value="실버라이트 값 자겨오기" />
<input type="button"  onclick="TestBtn2('kojaedoo')" value="실버라이트 값 세팅하기" />


    </form>
</body>
</html>

 

SilverlightService.svc 추가 합니다

public string Test() {

     return "kojaedoo";
}

메소드 추가

 

ISilverlightService.cs 파일에도  같은 함수 추가

[OperationContract]
string Test();

 

이것으로 웹서비스는 준비 끗

 

실버라이트 Page.xaml

private void Test()
     {
         EndpointAddress defaultAddress;
         ServiceRef.SilverlightServiceClient sc;
         Binding defaultBinding = new System.ServiceModel.BasicHttpBinding();
         defaultAddress = new System.ServiceModel.EndpointAddress("http://localhost:56445/SilverlightService.svc");
         sc = new NewCitiZenBasic.ServiceRef.SilverlightServiceClient(defaultBinding, defaultAddress);
         sc.TestAsync();
         sc.TestCompleted += new EventHandler<NewCitiZenBasic.ServiceRef.TestCompletedEventArgs>(sc_TestCompleted);
     }

 

     void sc_TestCompleted(object sender, NewCitiZenBasic.ServiceRef.TestCompletedEventArgs e)
     {
         MessageBox.Show(e.Result);
     }
     #endregion

 

 

웹서비스 테스트에서는 특정포트를 설정해놓으면 테스트하기 편리합니다.

복합 응용 프로그램 라이브러리를 기반으로 응용 프로그램은 잠재적으로 많은 느슨하게 결합된 복합 모듈로 구성되어있습니다. They need to interact with the shell to contribute content and receive notifications based on user actions. 그들은 껍질과 상호 작용하는 내용을 기반으로 사용자의 동작에 기여하고 알림을받을 필요가있다. Because they are loosely coupled, they need a way to interact and communicate with one another to deliver the required business functionality. 왜냐하면 그들은 느슨하게 결합하는, 그들은 서로 상호 작용하고 필요한 비즈니스 기능을 제공하는 의사 소통 방법이 필요합니다.

To tie together these various modules, applications based on the Composite Application Library rely on a dependency injection container. 이러한 다양한 모듈을 함께 넥타이하려면, 응용 프로그램은 복합 애플 리케이션 라이브러리를 기반으로 의존성 주입 컨테이너에 의존하고있습니다. Dependency injection containers can reduce the dependency coupling between objects by providing the facility to instantiate instances of classes and manage their lifetime based on the configuration of the container. 의존성 주입 컨테이너 클래스의 인스턴스를 인스턴스하고 평생 관리하는 컨테이너의 구성에 따라 시설을 제공하여 개체 간의 종속성 커플링을 줄일 수있습니다. During the objects creation, the container injects any dependencies that the object has requested into it. 객체를 생성하는 동안 컨테이너 종속성을 해당 개체가 그것에 주사를 요청했습니다. If those dependencies have not yet been created, the container creates and injects them first. 이러한 종속성이 아직 만들어지지 않은 경우, 컨테이너를 생성하고 처음으로 그들을 주입했다. In some cases, the container itself is resolved as a dependency. 일부의 경우, 컨테이너 자체가 종속성으로 해결됩니다. For example, modules often get the container injected, so they can register their views and services with that container. 예를 들어, 자주 주입 컨테이너를 얻을, 모듈 그래서 그들은 자신의 견해와 서비스 컨테이너에 등록할 수있습니다.

There are several advantages of using a container: 거기에 컨테이너를 사용하는 몇 가지 장점이있습니다 :

  • A container removes the need for a component to have to locate its dependencies or manage their lifetimes. 컨테이너는 종속성을 찾을 수 또는 그들의 수명을 관리하는 구성 요소에 대한 필요성이 제거됩니다.
  • A container allows swapping the implementation of the dependencies without affecting the component. 한 컨테이너는 구성 요소에 영향을주지 않고 의존성의 구현 스와핑 수있습니다.
  • A container facilitates testability by allowing dependencies to be mocked. 한 컨테이너 의존성을 조롱 수 있도록함으로써 테스트 용이하게합니다.
  • A container increases maintainability by allowing new components to be easily added to the system. 컨테이너는 시스템에 새로운 구성 요소를 쉽게 추가할 수 있도록하여 유지력을 증가시킵니다.

 

 

응용 프로그램의 컨텍스트에서 복합 응용 프로그램을 도서관에, 거기에 컨테이너로 구체적인 이점도있습니다 : 기초

  • A container injects module dependencies into the module when it is loaded. 한 컨테이너는 모듈이 로드될 때 모듈에 종속성을 주입합니다.
  • A container is used for registering and resolving presenters and views. 컨테이너 등록 및 발표자 및 플레이를 해결하는 데 사용됩니다.
  • A container creates presenters and presentation models and injects the view. 컨테이너 발표자와 프레 젠 테이션 모델을 생성하고보기를 주입했다.
  • A container injects the composition services, such as the region manager and the event aggregator. 컨테이너 지역 매니저와 이벤트 어그리게이터를 조성 등 서비스, 주사.
  • A container is used for registering module-specific services, which are services that have module-specific functionality. 컨테이너는 특정 기능이 서비스 모듈 - - 특정 서비스, 모듈을 등록하는 데 사용됩니다.

 

 

다음 코드를 주입하는 방법을 작동을 보여줍니다. When the PositionModule 언제 PositionModule is created by the container, it is injected with the regionManager and the container. 컨테이너에 의해 생성되고, 그것은 regionManager와 컨테이너와 주입니다. In the RegisterViewsAndServices method, which is called from the module's Initialize method, when the module is loaded, various services, views, and presenters are registered. 어떤 모듈이 로드될모듈의 초기화 방법, 다양한 서비스, 플레이에서 호출하는 방법을 RegisterViewsAndServices, 발표자 및 등록되어있습니다.

public PositionModule(IUnityContainer container, IRegionManager regionManager)
{
    _container = container;
    _regionManagerService = regionManager;
}

public void Initialize()
{
    RegisterViewsAndServices();
    ...
}

protected void RegisterViewsAndServices()
{
    _container.RegisterType<IAccountPositionService, AccountPositionService>(new ContainerControlledLifetimeManager());
    _container.RegisterType<IPositionSummaryView, PositionSummaryView>();
    _container.RegisterType<IPositionSummaryPresentationModel, PositionSummaryPresentationModel>();
    ...
}

 

컨테이너를 사용하여

Containers are used for two primary purposes, namely registering and resolving. 컨테이너 두 가지 기본적인 목적, 즉 해결하기위한 등록 및 사용되고있다.

Registering 등록

Before you can inject dependencies into an object, the types of the dependencies need to be registered with the container. 전에 종속성을 주입할 수있는 개체로, 의존성의 유형은 컨테이너에 등록해야합니다. Registering a type involves passing the container an interface and a concrete type that implements that interface. 등록 유형 컨테이너 수있는 인터페이스와 그 인터페이스를 구현하는 구체적인 유형을 통과한다. There are primarily two means for registering types and objects: through code or through configuration. 그 종류와 개체를 등록은 주로 두 가지 의미 : 코드를 통해 또는 구성됩니다. The specific means vary from container to container. 특정 의미 컨테이너를 컨테이너에 이르기까지 다양합니다.

Typically, there are two ways of registering types and objects in the container through code: 일반적으로, 거기에 코드를 통해 컨테이너의 종류와 개체 등록의 두 가지 방법이있습니다 :

  • You can register a type or a mapping with the container. 당신은 형식이나 컨테이너와 매핑을 등록할 수있습니다. At the appropriate time, the container will build an instance of the type you specify. 적절한시기에, 컨테이너를 지정하는 유형의 인스턴스를 구축할 예정이다.
  • You can register an existing object in the container. 당신이 컨테이너에있는 기존 개체를 등록할 수있습니다. The container will return a reference to the existing object. 이 컨테이너는 기존의 개체에 대한 참조를 반환합니다.

 

 

C # EmployeeModule.cs

this.container.RegisterType <IEmployeesController, EmployeesController> (); 

앞의 코드 예제에서, 당신은 어떻게 EmployeesController the IEmployeesController 인터페이스는 첫 전술된 접근법을 사용해서 등록되는 것을 볼 수있습니다. For an example of entering configuration information through the Unity container, see Entering Configuration Information . the 통합 컨테이너를 통해 구성 정보를 입력하는 예를 들어, 입력 구성 정보를 참조하십시오.

Types registered with the container have a lifetime. 종류의 컨테이너로 등록 일생. This can be either singleton (a single instance for the container, so each time you resolve you get the same instance) or instance (each time you resolve you get a new instance). 이 중 하나씩 컨테이너 (단일 인스턴스를, 그래서 당신이) 동일한 인스턴스를 얻을 또는 예를 들어 당신이 새 인스턴스를 얻을 해결 (각 시간)를 해결 할 때마다 수있습니다. The lifetime can be specified at registration or through configuration. 수명을 등록 또는 구성을 통해 지정할 수있습니다. The default lifetime depends on the container implementation. 기본값은 평생 컨테이너 구현에 따라 달라집니다. For example, the Unity container registers services as instances by default. 예를 들어, 기본적으로 인스턴스로 통합 컨테이너에 등록 서비스를 제공합니다.

 

다음 코드 예제는 어디 EmployeesPresenter 컨테이너에 의해 해결되고있다 보여줍니다.

C# EmployeeModule.cs

EmployeesPresenter 발표자 = this.container.Resolve <EmployeesPresenter> (); 

 

The Employee s Presenter constructor contains the following dependencies, which are injected when it is resolved.

public EmployeesPresenter(IEmployeesView view, IEmployeesListPresenter listPresenter, IEmployeesController employeeController)
    {
        this.View = view;
        this.listPresenter = listPresenter;
        this.listPresenter.EmployeeSelected += new EventHandler<DataEventArgs<BusinessEntities.Employee>>(this.OnEmployeeSelected);
        this.employeeController = employeeController;
        View.SetHeader(listPresenter.View);
    }

컨테이너를 사용하기위한 고려 사항

You should consider the following before using containers: 당신이 컨테이너를 사용하기 전에 다음 사항을 고려해야합니다 :

  • Consider whether it is appropriate to register and resolve components using the container: 등록 여부를 적절하고 해결 구성 요소는 컨테이너 사용을 고려 :
    • Consider whether the performance impact of registering in the container and resolving instances from it is acceptable in your scenario. 컨테이너에 등록 여부와 그것의 인스턴스를 해결의 성능에 미치는 영향을 고려하여 시나리오에서 사용할 수있습니다. For example, if you need to create 10,000 polygons to draw a surface within the local scope of a rendering method, the cost of resolving all of those polygon instances through the container might have a significant performance cost because of the container's use of reflection for creating each entity. 예를 들어, 만약 당신이 렌더링 방식의 지역 범위 내에서 표면 무승부로 10,000 다각형을 만들, 컨테이너를 통해 모든 이들 다각형 인스턴스의 해결의 비용 컨테이너의 성능 때문에 상당한 비용을 만들기위한 반성의 사용을 가지고있을 필요 각 엔티티.
    • If there are many or deep dependencies, the cost of creation can increase significantly. 많은 경우에는 또는 깊은 의존성, 창조의 비용을 크게 증가시킬 수있다.
    • If the component does not have any dependencies or is not a dependency for other types, it may not make sense to put it in the container. 어떤 의존성이없는 경우 또는 다른 유형의 구성 요소에 대한 종속성이없는 경우, 그것은 용기에 넣어 이해가되지 않을 수있습니다.
  • Consider whether a component's lifetime should be registered as a singleton or instance: 평생 a 싱글톤 여부 또는 구성 요소의 인스턴스로 등록해야한다 고려 :
    • If the component is a global service that acts as a resource manager for a single resource, such as a logging service, you may want to register it as a singleton. 하는 경우 구성 요소는 로깅 서비스와 같은 하나의 리소스에 대한 리소스 매니저의 역할을, 당신은 싱글톤으로 등록을 원하는 수있는 글로벌 서비스입니다.
    • If the component provides shared state to multiple consumers, you may want to register it as a singleton. 상태를 공유하는 경우에는 구성 요소가 여러 소비자에게 제공하고, 당신은 싱글톤으로 등록을 할 수있습니다.
    • If the object that is being injected needs to have a new instance of it injected each time a dependent object needs one, register it as a non-singleton. 만약 객체가 그것의 새 인스턴스가 필요 주입되고 각 시간 종속 개체, 하나의 요구가 아닌 - 싱글톤으로 등록을 주입했다. For example, each Presentation Model needs a new instance of a view. 예를 들어, 각 프레 젠 테이션 모델 뷰의 새 인스턴스가 필요합니다.
  • Consider whether you want to configure the container through code or configuration: 여부를 구성 컨테이너에 코드 또는 구성을 통해 원하는 고려 :
    • If you want to centrally manage all the different services, configure the container through configuration. 만일 중앙에서 구성을 통해 컨테이너를 구성하는 다른 모든 서비스를 관리하고자합니다.
    • If you want to conditionally register specific services, configure the container through code. 만약 당신이 조건부 코드를 통해 특정 서비스를 구성 컨테이너 등록 싶어요.
    • If you have module-level services, consider configuring the container through code so that those services are only registered if the module is loaded. 모듈 - 수준의 서비스를 받아야하는 경우, 코드를 통해 모듈이로드되는 경우에만 해당 서비스에 등록하고있는 컨테이너를 구성한다.

모듈화 ()가 큰 응용 프로그램으로 구성되어있을 수있는 모듈의 이름은 그 기능 단위의 집합으로 구성되어있습니다 시스템 설계하고있다. A module represents a set of related concerns.

모듈 관련 우려의 집합을 나타냅니다.

It can include a collection of related components, such as features, views, or business logic, and pieces of infrastructure, such as services for logging or authenticating users.

그것은, 로직 기능, 플레이, 또는 사업과 같은 관련 구성 요소의 컬렉션을 포함시킬 수 및 로깅 또는 사용자를 인증하는 서비스와 같은 인프라의 조각,.

Modules are independent of one another but can communicate with each other in a loosely coupled fashion.

모듈은 서로 독립적입니다하지만 각각 느슨하게 결합된 방식으로 서로 통신할 수있습니다.

A composite application exhibits modularity.

종합 응용 프로그램을 전시하고 모듈화. For example, consider an online banking program.

예를 들어, 온라인 뱅킹 프로그램을 고려해보십시오.

The user can access a variety of functions, such as transferring money between accounts, paying bills, and updating personal information from a single user interface (UI).

사용자는, 세금 계산서 등 다양한 기능의 계정 간의 자금 이동으로 액세스 할 수 있으며 단일 사용자 인터페이스 (UI)에서 개인 정보를 업데이 트했다.

However, behind the scenes, each of these functions is a discrete module.

그러나이 장면 뒤에, 각각의 이러한 기능의 개별 모듈입니다. These modules communicate with each other and with back-end systems such as database servers.

이러한 모듈은 서로를 다시 데이터베이스 서버와 통신할 - 엔드 시스템 등.

Application services integrate components within the different modules and handle the communication with the user.

응용 프로그램 서비스는 다른 모듈 내의 구성 요소를 통합하고 사용자와의 커뮤니케이 션을 처리합니다. The user sees an integrated view that looks like a single application.

사용자가 볼 수있는 통합 뷰가 하나의 응용 프로그램처럼 보인다.

Figure 1 illustrates a design of a composite application with multiple modules.

그림 1은 여러 개의 모듈을 가진 복합 애플 리케이션의 디자인을 보여줍니다.

 

Dd490825.ModularityDCFig1 (엉 - 우리, MSDN.10)의 PNG.

 

모듈형 디자인을 선택하는 이유는?

The following scenarios describe why you might want to choose a modular design for your application:

다음 시나리오는 이유 때문에 당신이 애플 리케이션을위한 모듈형 디자인을 선택할 수있습니다 설명 :

  • Simplified modules . 간체 모듈을 제공합니다. Properly defined modules have a high internal cohesion and loose coupling between modules.
  • 제대로 정의된 모듈 높은 내부 응집력와 모듈 사이의 느슨한 결합.
  • The coupling between the modules should be through well-defined interfaces.
  • 이 모듈 사이의 결합을 통해 잘 - 정의된 인터페이스를해야한다.
  • Developing and/or deploying modules independently. Modules can be developed, tested, and/or deployed on independent schedules when modules are developed in a loosely coupled way.
  • 개발 / 또는 독립적으로 모듈을 배포합니다. 모듈, 테스트 및 개발 될 수있는 / 또는 독립적인 일정을 때 느슨하게 결합된 모듈 방식으로 개발에 배치했다. By doing this, you can do the following:
  • 이렇게하면 다음 작업을 수행할 수있습니다 :
    • You can independently version modules. 당신이 수있는 독립적 버전의 모듈을 제공합니다.
    • You can develop and test modules in isolation. 당신이 개발할 수와 고립에 모듈을 테스트합니다.
    • You can have modules developed by different teams. 당신은 다른 팀들에 의해 개발된 모듈을 가질 수있습니다.
  • Loading modules from different locations .
  • 서로 다른 위치에서로드 모듈. A Windows Presentation Foundation (WPF) application might retrieve modules from the Web, from the file system and/or from a database.
  • 파일 시스템 및 데이터베이스 / 또는에서 윈도우 프리젠 테이션 파운데이션 (WPF) 응용 프로그램은 웹에서 모듈을 검색할 수도있다.
  • A Silverlight application might load modules from different XAP files.
  • 한 XAP 파일에서 실버 라이트 응용 프로그램을 다른 모듈을 로드할 수있습니다.
  • However, most of the time, the modules come from one location;
  • for example, there is a specific folder that contains the modules or they are in the same XAP file.
  • 그러나, 대부분의 시간,이 모듈을 하나의 위치에서 온; 예를 들면, 그 모듈이 포함되어하거나 동일한 XAP 파일에있는 특정 폴더입니다.
  • Minimizing download time . 다운로드 시간을 최소화했다.
  • When the application is not on the user's local computer, you want to minimize the time required to download the modules. 때 응용 프로그램은 사용자의 로컬 컴퓨터에없는 경우, 당신의 모듈을 다운로드하는 데 필요한 시간을 최소화하기 위해 싶어요.
  • To minimize the download time, only download modules that are required to start-up the application. 다운로드 시간을 최소화하기 위해, 그 시작에 - 응용 프로그램을 다운로드 모듈에만 필요합니다.
  • The rest are loaded and initialized in the background or when they are required. 로드되고 나머지는 배경에서 초기화 또는 그들이 필요합니다.
  • Minimizing application start-up time . 응용 프로그램을 시작할 - 시간을 최소화했다. To get part of the application running as fast as possible, only load and initialize the module(s) that are required to start the application. 모듈 (들)은 응용 프로그램을 시작하는 데 필요한 응용 프로그램을 최대한 빨리, 가능한 한 유일한로드 및 초기화를 실행의 일부를 얻으려면.
  • Loading module s 로드 모듈 s based on rules . 규칙을 기반으로합니다. This allows you to only load modules that are applicable for a specific role. 이것은 특정 역할에 적용되는 전용 모듈을 로드할 수있습니다. An application might retrieve from a service the list of modules to load. 한 응용 프로그램 모듈의 목록을 검색할 수있는 서비스에서 로드할 수있습니다.

Designing a Modular System 모듈형 시스템 설계

When you develop in a modularized fashion, you structure the application into separate modules that can be individually developed, tested, and deployed by different teams. 패션 modularized 개발하면, 당신은 개별적으로 개발할 수있을 테스트를 별도의 모듈을, 그리고 다른 팀들에 의해 배치로 응용 프로그램을 구조했다. Modules can enforce separation of concerns by vertically partitioning the system and keeping a clean separation between the UI and business functionality. 모듈을 수직으로 시스템 파티션과 깔끔한 UI와 비즈니스 기능 사이의 분리를 유지하여 우려의 분리를 적용할 수있습니다. Not having modularity makes it difficult for the team to introduce new features and makes the system difficult to test and to deploy. 모듈화가 어려운 팀이 아니라 새로운 기능에 대한 소개를하고 시스템을 테스트하고 배포하기 어려워합니다.

The following are general guidelines for developing a modular system: 다음은 모듈러 시스템을 개발하기위한 일반적인 가이드라인은 무엇입니까 :

  • Modules should be opaque to the rest of the system and initialized through a well-known interface. 모듈은 시스템의 나머지를 투과해야하며 잘 - 알려진 인터페이스를 통해 초기화.
  • Modules should not directly reference one another or the application that loaded them. 모듈해야 하나의 직접적인 원인은 아니 참조하거나 그들 로드된 다른 응용 프로그램이있습니다.
  • Modules should use loosely coupled techniques, such as shared services, to communicate with the application or with other modules, instead of communicating directly. 모듈을 공유하는 서비스와 같은 응용 프로그램이나 다른 모듈과 함께, 의사 소통의 직접 의사 소통을 대신 느슨하게 결합된 기법을 사용해야합니다.
  • Modules should not be responsible for managing their dependencies. 모듈들의 의존성을 관리하기위한 책임을지지해서는 안된다. These dependencies should be provided externally, for example, through dependency injection. 이러한 종속성이 외부 의존성을 주입, 예를 들면,를 통해 제공되어야한다.
  • Modules should not rely on static methods that can inhibit testability. 모듈 테스트 억제할 수 정적 방법에 의존해서는 안된다.
  • Modules should support being added and removed from the system in a pluggable fashion. 추가되는 모듈을 지원해야하고 플러그 패션에서 시스템에서 제거됩니다.

When you design a modular system, consider the following steps: 모듈러 시스템을 설계하면, 다음 단계를 고려 :

  1. Define the goals for the modular design. 모듈러 설계를위한 목표를 정의합니다. As described earlier, there are several reasons why you might decide to implement a modular design for your application. 앞에서 설명한대로, 거기에 왜 당신의 애플 리케이션을위한 모듈식 설계를 시행하기로 결정 데는 몇 가지 이유가있다.
  2. Decide how you are going to partition your modules and define your module's responsibilities. 어떻게하면 모듈과 모듈의 책임을 정의하는 파티션에 갈 곳을 결정합니다. Each module should have a distinct set of responsibilities. 각 모듈의 책임은 별개의 설정이 있어야합니다. The most common approach is to partition your application so that each module has its own functional area, such as Customers or Orders. 가장 일반적인 접근 때문에 각 모듈은 고객이나 주문과 같은 기능 영역 자체가 귀하의 응용 프로그램 파티션을하는 것입니다. In this case, each module will consist of its own presentation layer, a business or domain layer, and a resource access layer. 이 경우에는 각 모듈은 자신의 프레 젠 테이션 레이어, 비즈니스 또는 도메인 계층 및 리소스에 액세스 레이어의 구성된다. Figure 2 illustrates an example where a module that addresses a specific functional area contains all these logical layers. 그림 2는 어디 모듈 주소가 특정 기능 영역에서 예를 설명이 논리적 레이어를 포함하고있습니다.

    Dd490825.ModularityFig1 (엉 - 우리, MSDN.10)의 PNG.

    Figure 2 그림 2
    Layered approach to module design 중층적인 접근 방식 설계 모듈

    There are other ways to approach the design of modules. 거기에 다른 모듈의 디자인에 접근하는 방법이있습니다. For example, if you want to make it easier to replace the UI of your application, it might make sense to place the presentation layer in one or more easy-to-replace modules. 만약 여러분의 애플 리케이션의 UI를 쉽게 대체할 수 있도록하고 싶지 예를 들어, 하나 이상의 프레 젠 테이션 레이어는 쉬운 곳으로 감각을 만들어 야지 - - 모듈을 대체할 수있습니다. If you want your application to support different resource-access strategies, another example might be to put your resource access layer in a separate module. 만약 당신이 다른 리소스 - 액세스 전략을 지원하는 응용 프로그램을 원하는 또 다른 예제는 별도의 모듈에서 귀하의 리소스에 액세스 레이어를 잠재울 수있습니다. By replacing the resource access layer module, you can have the application access a local database or a remote Web service. 리소스에 대한 액세스 레이어 모듈을 교체함으로써, 애플 리케이션 액세스, 로컬 데이터베이스 또는 원격 웹 서비스를 할 수있습니다.

  3. Define the communication patterns between the modules. 이 모듈 사이의 통신 패턴을 정의합니다.

    Even though modules should have low coupling between each other, it is common for modules to communicate with each other. 비록 서로 모듈, 모듈에 대한 서로 간의 의사 소통을하는 것이 일반적입니다 낮은 커플링이 있어야합니다. There are several loosely coupled communication patterns, each with their own strengths. 몇 가지를 느슨하게 결합된 커뮤니케이션 패턴, 각자의 강점이있다. Typically, combinations of these patterns are used to create the resulting solution. 일반적으로 이러한 패턴의 조합 결과가 솔루션을 만드는 데 사용됩니다. The following are some of these patterns: 다음의 몇 가지 패턴의 위치 :

    • Loosely coupled events . 느슨하게 결합된 이벤트. A module can broadcast that a certain event has occurred. 모듈을 특정 이벤트가 발생했습니다 방송하실 수있습니다. Other modules can subscribe to those events so they will be notified when the event occurs. 다른 모듈이 그 행사를 구독할 수 있도록 그들이 통보됩니다 이벤트가 발생할 때. Loosely coupled events are a lightweight manner of setting up communication between two modules; therefore, they are easily implemented. 느슨하게 결합된 이벤트를 두 모듈 간의 통신을 설정하는 방식의 경량; 그러므로, 그들은 쉽게 구현됩니다. However, a design that relies too heavily on events can become hard to maintain, especially if many events have to be orchestrated together to fulfill a single task. 그러나 디자인이 너무 무겁게 이벤트에 의존하고 유지하기 위해, 특히 다양한 이벤트가 함께하는 경우는 하나의 임무를 완수하기 위해 조율된 게 쉽지가 될 수있다. In that case, it might be better to consider a shared service. 그런 경우엔, 공유 서비스를 고려하는 것이 좋을 것입니다.
    • Shared services . 공유 서비스를 제공합니다. A shared service is a class that can be accessed through a common interface. 공유 서비스는 일반적인 인터페이스를 통해 액세스할 수있는 클래스입니다. Typically, shared services are found in a shared assembly and provide system-wide services, such as authentication, logging, or configuration. 일반적으로 공유하는 서비스는 공유 어셈블리에서 발견하는 시스템을 제공하고 인증과 같은 - 넓은 서비스, 로깅, 또는 구성.
    • Shared resources . 공유 자원. If you do not want modules to directly communicate with each other, you can also have them communicate indirectly through a shared resource, such as a database or a set of Web services. 만약 당신이 직접 서로 통신 모듈을 원하지 않으면, 당신도 그들을 간접적으로 공유 리소스를 통해, 데이터베이스 또는 웹 서비스의 설정 등과 같은 의사 소통을 할 수있습니다.

Team Development Using Modules 팀 개발을 사용하여 모듈

Modules have explicit boundaries, typically by subsystem or feature. 모듈, 서브 시스템 또는 기능은 일반적으로 명시적인 한계가있다. Having these boundaries makes it easier for separate teams to develop modules. 이러한 경계가 쉽게 모듈을 개발할 수 있도록 별도의 팀이있다. On large applications, teams may be organized by cross-cutting capabilities in addition to being organized by a specific subsystem or feature. 대형 응용 프로그램에서 크로스로 팀을 구성할 수있습니다 - 절삭 기능 이외에 특정 서브 시스템 또는 기능에 의해 조직되고있다. For example, there may be a team assigned to shared components of the application, such as the shell or the common infrastructure module. 예를 들어, 한 팀을 거기 응용 프로그램의 공유 구성 요소, 셸 또는 공통 인프라 모듈 등 할당될 수있습니다.

The following are the different teams developing the Stock Trader Reference Implementation, as illustrated in Figure 3: 다음은 다른 팀들은 주식 트레 이더 참조 구현을 개발,으로 그림 3에서 보여주고있습니다 :

  • Infrastructure team . 인프라 팀. This team develops the core cross-cutting services used in the application and cross-module types and interfaces. 이 팀의 핵심 크로스 - 서비스는 응용 프로그램과 교차에 사용되는 - 모듈 유형과 인터페이스를 절단을 개발하고있습니다.
  • Pos i tions team . 포지션 내가 팀을 참조하십시오. This team maintains the Positions and Buy/Sell functionality. 이 팀의 순위를 유지 관리 및 주문 / 기능을 매도했다.
  • News team . 뉴스 팀. This team handles aggregating and displaying news. 이 팀은 합칩니다 핸들 및 뉴스를 표시합니다.
  • UI team . UI를 팀. This team manages the shell and contains a set of graphic designers who set the overall appearance of the application. 이 팀은 껍질을 관리하고 응용 프로그램의 전체적인 모양을 설정 그래픽 디자이너의 세트가 포함되어있습니다. They work across each of the development teams. 그들은 각 팀들의 전체 개발 작업.
  • Operation s team . 작전 팀. This team is responsible for managing and deploying modules to staging and production. 이 팀 관리 및 준비 및 생산에 모듈을 배포하기위한 책임이있다. They also manage the master module configuration files. 그들은 또한 모듈 구성 파일은 마스터를 관리할 수있습니다.

Figure 3 illustrates an example of a composite application's modules and associated teams. 그림 3은 응용 프로그램의 모듈과 관련된 종합 팀의 예를 보여줍니다.

Dd490825.ModuleDesignFig3 (엉 - 우리, MSDN.10)의 PNG.

RSS 기사받아오기

WEF 웹서비스를 사용하기 위한 기본설정

      <service behaviorConfiguration="SLApp.Web.WCFServiceBehavior"
        name="SLApp.Web.WCFService">
        <!--
        <endpoint address="" binding="wsHttpBinding" contract="SLApp.Web.IWCFService">
          -->
        <endpoint address="" binding="basicHttpBinding" contract="SLApp.Web.IWCFService">

          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  </system.serviceModel>
</configuration>

WCF 웹서비스

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
using System.Xml.Linq;
namespace SLApp.Web
{
    // NOTE: If you change the class name "WCFService" here, you must also update the reference to "WCFService" in Web.config.
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class WCFService : IWCFService
    {
        public void DoWork()
        {
        }

        public List<WCFDataType.RSS2_0> GetNewsRSS() {

            List<WCFDataType.RSS2_0> rss = new List<SLApp.Web.WCFDataType.RSS2_0>();
            XDocument rssFeed = XDocument.Load("http://news.kbs.co.kr/rss/kbsrss_news.php?site=news");
            var posts = from item in rssFeed.Descendants("item")
                        select new
                        {
                            Title = item.Element("title").Value,
                            Published = DateTime.Parse(item.Element("pubDate").Value),
                            Description = item.Element("description").Value,
                            Link = item.Element("link").Value,
                            Author = item.Element("author").Value
                        };

            foreach (var s in posts)
            {
                rss.Add(new SLApp.Web.WCFDataType.RSS2_0(s.Title, s.Author, s.Published, s.Description, s.Link));
            }

            return rss;
        }

------------------------------------------------------------------------------------------

//또다른 방법

      public  void Stock()
        {
            WebClient client = new WebClient();
            string s = client.DownloadString(new Uri("주식정보"));
            s = s.Trim();
            XDocument doc = XDocument.Parse(s);
            IEnumerable<XElement> current = doc.Element("StockInfo")
                .Element("channel")
                .Element("Stock_Sise")
                .Elements();
            Response.Write(current.ElementAt(0).Value);
        }

실제 받아오는 정보

<?xml version="1.0" encoding="euc-kr" ?>

- <StockInfo>

- <channel>

- <Stock_Sise>

<StockName>삼성전자</StockName>

<CurrentPoint>17,2500</CurrentPoint>

<UpDownPoint>50</UpDownPoint>

<UpDownFlag>2</UpDownFlag>

<UpDownSign></UpDownSign>

</Stock_Sise>

</channel>

</StockInfo>

------------------------------------------------------------------------------------------

    }
}

실버라이트에서 공유할 데이터

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

using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
using System.Xml.Linq;

namespace SLApp.Web.WCFDataType
{
    [DataContract]
    public class RSS2_0
    {

        public RSS2_0(string p_Title, string p_Author, DateTime p_PubDate, string p_Description, string p_Link)
        {
            this.Title = p_Title;
            this.Author = p_Author;
            this.PubDate =p_PubDate;
            this.Description = p_Description;
            this.Link = p_Link;
        }
        private string _Title;
        private string _Description;
        private string _Author;
        private DateTime _PubDate;
        private string _Link;

        [DataMember]
        public string Title
        {
            get { return _Title; }
            set { _Title = value; }
        }

        [DataMember]
        public string Description
        {
            get { return _Description; }
            set { _Description = value; }
        }

        [DataMember]
        public string Author
        {
            get { return _Author; }
            set { _Author = value; }
        }

        [DataMember]
        public DateTime PubDate
        {
            get { return _PubDate; }
            set { _PubDate = value; }
        }

        [DataMember]
        public string Link
        {
            get { return _Link; }
            set { _Link = value; }
        }

    }
}

실버라이트

using System.Xml.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Collections.ObjectModel;
namespace PCGEP.SLApp.Contents
{
    public partial class NoticeNewsRSS : UserControl
    {
        public NoticeNewsRSS()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(NoticeNewsRSS_Loaded);
        }

        void NoticeNewsRSS_Loaded(object sender, RoutedEventArgs e)
        {

            Binding defaultBinding = new System.ServiceModel.BasicHttpBinding();
            EndpointAddress defaultAddress = new System.ServiceModel.EndpointAddress(@"http://localhost:9917/WCFService.svc");

            WCFServiceReference.WCFServiceClient  wc = new PCGEP.SLApp.WCFServiceReference.WCFServiceClient(defaultBinding, defaultAddress);
            wc.GetNewsRSSCompleted += new EventHandler<PCGEP.SLApp.WCFServiceReference.GetNewsRSSCompletedEventArgs>(wc_GetNewsRSSCompleted);
            wc.GetNewsRSSAsync();

        }

        void wc_GetNewsRSSCompleted(object sender, PCGEP.SLApp.WCFServiceReference.GetNewsRSSCompletedEventArgs e)
        {
            this.rssListBox.ItemsSource = e.Result;
        }
    }
}

실버라이트 초간단 데이터 바인딩

1.ADO.NET Entity Data Model 을 만듭니다 (서버측)

image

2. 그런다음 데이터베이스에 접근할수 있는 ado.net Data Service 를 만들어줍니다. (서버측)

image

만들어진 Ado.Net Data Service

image

3.실버라이트 프로젝트에서 웹서비스를 참조합니다.

image

4.데이터그리드에 데이터를 바인딩 합니다.

아래는 간단한 소스

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using System.Data.Services.Client;
using System.Collections.ObjectModel;
using System.ComponentModel;
using BM.ServiceReference1;
namespace BM.CodeTest
{
    public partial class Delete : UserControl
    {
        ServiceReference1.TEST_BOOKEntities svcContext;
        ObservableCollection<ServiceReference1.BOOK> ObsvBookCollrection;
        BooksDS bookDs;


        public Delete()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Delete_Loaded);
        }

        void Delete_Loaded(object sender, RoutedEventArgs e)
        {

            svcContext = new TEST_BOOKEntities(new Uri("BookWebDataService.svc", UriKind.Relative));
            ObsvBookCollrection = new ObservableCollection<BOOK>();
            bookDs = new BooksDS();
            DataServiceQuery<BOOK> query = (DataServiceQuery<BOOK>)
                (from c in svcContext.BOOK select c);
            query.BeginExecute(GetDataCallback, query);

        }

 

        #region 셀렉트

        void GetDataCallback(IAsyncResult result)
        {

            try
            {
                DataServiceQuery<BOOK> queryResult =
                               (DataServiceQuery<BOOK>)result.AsyncState;

                IEnumerable<BOOK> results =
                              queryResult.EndExecute(result);

                foreach (var item in results)
                {
                    bookDs.Add(item);
                }
                    grdList.ItemsSource = bookDs;
   
              
                

                MessageBox.Show("도서목록가져오기 완료");

            }
            catch (DataServiceRequestException ex)
            {

            }


        }
        #endregion


    }
}


5.테스트 끝~

// Custom class implements the IValueConverter interface.
public class DateToStringConverter : IValueConverter
{

    #region IValueConverter Members

    // Define the Convert method to change a DateTime object to a month string.
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // value is the data from the source object.
        DateTime thisdate = (DateTime)value;
        int monthnum = thisdate.Month;
        string month;
        switch (monthnum)
        {
            case 1:
                month = "January";
                break;
            case 2:
                month = "February";
                break;
            default:
                month = "Month not found";
                break;
        }
        // Return the value to pass to the target.
        return month;

    }

    // ConvertBack is not implemented for a OneWay binding.
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

 

 

사용법

  1. <Grid.Resources>  
  2.  
  3.     <DataTemplate x:Name="dataTemplate">  
  4.         <Grid>  
  5.             <Grid.ColumnDefinitions>  
  6.                 <ColumnDefinition />  
  7.                 <ColumnDefinition />  
  8.             </Grid.ColumnDefinitions>  
  9.             <TextBlock Grid.Column="0" Text="{Binding Month, Converter={StaticResource Converter1}}"/>  
  10.             <TextBlock Grid.Column="1" Text="{Binding Total}"/>      
  11.        </Grid>  
  12.     </DataTemplate>  
  13.  
  14. </Grid.Resources>  
  15.  
  16. <ItemsControl x:Name="IC1" ItemsSource="{Binding}" ItemTemplate="{StaticResource dataTemplate}"/> 

 

INotifyPropertyChanged 인터페이스는 속성 값이 변경되었음을 클라이언트(대개 바인딩하는 클라이언트)에 알리는 데 사용됩니다.

예를 들어, FirstName이라는 속성이 있는 Person 개체의 경우 제네릭 속성 변경 알림을 제공하기 위해 Person 형식은 INotifyPropertyChanged 인터페이스를 구현하고 FirstName이 변경될 때 PropertyChanged 이벤트를 발생시킵니다.

다음 코드 예제에서는 INotifyPropertyChanged 인터페이스를 구현하는 방법을 보여 줍니다.

//Add using statements
using System.ComponentModel;
using System.Windows.Data;


...


// Create a class that implements INotifyPropertyChanged
public class Person : INotifyPropertyChanged
{
    private string firstNameValue;
    public string FirstName{
        get { return firstNameValue; }
        set
        {
            firstNameValue=value;
            // Call NotifyPropertyChanged when the property is updated
            NotifyPropertyChanged("FirstName");
        }
    }

    // Declare the PropertyChanged event
    public event PropertyChangedEventHandler PropertyChanged;

    // NotifyPropertyChanged will raise the PropertyChanged event passing the
    // source property that is being updated.
    public void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }  
}

 

 

 

또다른 예제

// Create a class that implements INotifyPropertyChanged.
public class MyColors : INotifyPropertyChanged
{
    private SolidColorBrush _Brush1;

    // Declare the PropertyChanged event.
    public event PropertyChangedEventHandler PropertyChanged;

    // Create the property that will be the source of the binding.
    public SolidColorBrush Brush1
    {
        get { return _Brush1; }
        set
        {
            _Brush1 = value;
            // Call NotifyPropertyChanged when the source property is updated.
            NotifyPropertyChanged("Brush1");
        }
    }


    // NotifyPropertyChanged will raise the PropertyChanged event, passing 
    // the source property that is being updated.
    public void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

유저컨트롤

namespace BM.CodeTest
{
    public delegate void PagerChangeIndex( string pageIndex ); //델리게이트 선언
    public partial class DelegateTestControl : UserControl
    {
        public event PagerChangeIndex pagerChangeIndex;
        public DelegateTestControl()
        {
            InitializeComponent();
          
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                pagerChangeIndex("10");
            }
            catch (Exception ex) {

                MessageBox.Show("델리게이트 구현");
            }
        }
    }
}

 

 

페이지

namespace BM.CodeTest
{
    public partial class DelegateTest : UserControl
    {
        public DelegateTest()
        {
            InitializeComponent();
            this.Btn.pagerChangeIndex += new PagerChangeIndex(Btn_pagerChangeIndex); //델리게이트 이벤트 구현
            
        }

        void Btn_pagerChangeIndex(string pageIndex)
        {
            MessageBox.Show(pageIndex);  //   10이 표시됩니다.
        }


    }
}

1.데이터바인딩

바인딩 개체 만들기

namespace BusinessEntities
{
    public class Movies
    {
        public Movies(string Title) {

            this.Title = Title;
        
        }

        public string Title { set; get; }
    }
}

 

2.classMovies를 담을 ObservableCollection<BusinessEntities.Movies> 개체 생성

    public class AllMovies  :ObservableCollection<BusinessEntities.Movies>
    {
        public AllMovies() {

            this.Add(new BusinessEntities.Movies("제목"));
            this.Add(new BusinessEntities.Movies("제목"));
            this.Add(new BusinessEntities.Movies("제목"));
            this.Add(new BusinessEntities.Movies("제목"));
            this.Add(new BusinessEntities.Movies("제목"));

        }

        
    }

 

3.표시할 xaml (MovieList.xaml )만들기

   <ListBox x:Name="MyBooks" ItemsSource="{Binding Mode=OneWay}"  Margin="16,48,16,24" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" >
                      
                        <TextBlock Text="{Binding Title}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

 

4.바인딩하기 MovieList.xaml 비하인드 코드

	public partial class MovieList : UserControl
	{
        BusinessEntities.AllMovies am;
		public MovieList()
		{
			// 변수를 초기화하는 데 필요합니다.
			InitializeComponent();
            am = new BusinessEntities.AllMovies();
            MyBooks.DataContext = am;

		}




	}

 

------------------------------------------------------------------------------------------------

바인딩된 개체 알아내기

------------------------------------------------------------------------------------------------

이벤트 추가

<ListBox x:Name="MyBooks" ItemsSource="{Binding Mode=OneWay}"  Margin="16,48,16,24"   SelectionChanged="MyBooks_SelectionChanged">

비하인드 코드

//선택변경
private void MyBooks_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
     ListBox SelectMovies = sender as ListBox;
     BusinessEntities.Movies mv = SelectMovies.SelectedItem as BusinessEntities.Movies;
     MessageBox.Show(mv.Title); 

}

+ Recent posts