ASP.NET and Flex - Friendship Forever

I would like to devote this post to the possibility of integrating the two ASP.NET and Flex platforms.

Foreword

Flash is generally a great tool for creating rich multimedia projects, and with the release of ActionScript 3 and Flex technology, it has become a pleasure to program. At the same time, you can create both RIA and desktop applications (thanks, Adobe AIR).

On the other hand, we have ASP.NET - a powerful tool for creating web applications. You can use two completely different approaches to building the application: either use WebForms + Web Services, or ASP.NET MVC, adhering to the REST style.
Before finishing the digression, I would like to outline the tools that we need.
So this is -
  1. Visual Studio 2010 Professional
  2. Flash Builder 4 Standard


Meet FluorineFX

As an example, I would like to give an example of an application that will work with frequently updated data and synchronize with other clients. Typically, in the case of Flex, either AMF-streaming or RTMP-streaming is used. The FluorineFX library comes to the rescue to add server-side support. Project site and useful links here .

Cooking server

Before creating an ASP.NET application, we must create a library, which is a mini-server that encapsulates services and logic for clients. To do this, create a new library project in C # and name it ServiceLibrary.
To monitor active clients, you need to create a class that inherits from the MessagingAdapter and implements the ISessionListener interface.

publicclassAppAdapter : MessagingAdapter, ISessionListener
{
    publicAppAdapter()
    {
        ClientManager.AddSessionCreatedListener(this);
    }
    #region ISessionListener MemberspublicvoidSessionCreated(IClient client)
    {
        //Ваши действия при присоединении клиента
        client.AddSessionDestroyedListener(this);
    }
    publicvoidSessionDestroyed(IClient client)
    {
        //Ваши действия при разъединении клиента
    }
    #endregionpublicoverrideobjectInvoke(IMessage message)
    {
        //Здесь передается управление вашему коду для обработки пересылки сообщенийreturnnull;
    }
}

For clients working through remoting, we will create a service that will provide the API.


[RemotingService()]
publicclassDataService
{
    publicDataService()
    {
    }
    //Данный показательный метод будет использоваться клиентами. publicstringGetData()
    {
        return"Hello, world!";
    }
}

On this for now, the mini-server code is sufficient for use. Each instance of the class will be created when a new client connects and works in the same domain as the ASP.NET application.

Web Application Preparation

The web application will run on ASP.NET 4. To do this, create a new project in the studio.
To connect clients, FluorineFX uses a gateway, which is nothing more than a regular ASPX page, which Fluorine’s http module will process requests for. We will consider this question in more detail below, but for now we will add a regular ASP.NET page and call it Gateway.aspx.
Configure web.config
<configuration><configSections><sectionGroupname="fluorinefx"><sectionname="settings"type="FluorineFx.Configuration.XmlConfigurator, FluorineFx"requirePermission="false"/></sectionGroup></configSections><fluorinefx><settings><rtmpServer><threadpoolminWorkerThreads="0"maxWorkerThreads="25"idleTimeout="60000"/><rtmpConnectionpingInterval="0"maxInactivity="60000"maxHandshakeTimeout="0"/><rtmptConnectionpingInterval="5000"maxInactivity="60000"maxHandshakeTimeout="5000"/><rtmpTransportreceiveBufferSize="4096"sendBufferSize="4096"tcpNoDelay="true"/></rtmpServer></settings></fluorinefx><system.web><compilationdebug="true"targetFramework="4.0" /><httpModules><addname="FluorineGateway"type="FluorineFx.FluorineGateway,FluorineFx" /></httpModules></system.web><system.webServer><validationvalidateIntegratedModeConfiguration="false"/><modulesrunAllManagedModulesForAllRequests="true"><addname="FluorineGateway"type="FluorineFx.FluorineGateway, FluorineFx"/></modules></system.webServer></configuration>

I note that FluorineFX only works with configuration files located in the WEB-INF folder. This is how the server is configured for BlazeDS and LifeCycle Data Services.

Now create the configuration files. To do this, create the WEB-INF folder in the root directory and the flex subfolder.
Add an xml file called services-config.xml .
<?xml version="1.0" encoding="utf-8" ?><services-config><services><service-includefile-path="remoting-config.xml" /><service-includefile-path="messaging-config.xml" /></services><channels><channel-definitionid="my-amf"class="mx.messaging.channels.AMFChannel"><endpointuri="http://{server.name}:{server.port}/Gateway.aspx"class="flex.messaging.endpoints.AMFEndpoint"/><properties><!-- <legacy-collection>true</legacy-collection> --></properties></channel-definition><channel-definitionid="my-rtmp"class="mx.messaging.channels.RTMPChannel"><endpointuri="rtmp://{server.name}:1950"class="flex.messaging.endpoints.RTMPEndpoint"/></channel-definition></channels></services-config>

Above, we indicated 2 end-points: for AMF and RTMP channels, as well as the location of two configuration files for clients working via remoting and / or messaging. Add the remoting-config.xml and messaging-config.xml files to the same folder .

Flex Client

Now it's time to create a client. First, create a Flex project in Flash Builder. Next, open the project properties> Flex Compiler. In the "Additional compiler arguments" text box, add the following line -services "{project_location} \ WEB-INF \ flex \ services-config.xml" . And, of course, add a link to fds.swc to the project to enable RTMPChannel support. This library is part of the LCDS, but if there is no LCDS, then it is present in the files at the end of the article. In the application * .mxml file, paste the following code:
<fx:Declarations>
	<mx:Consumer id="consumer" destination="data_destination" message="messageHandler(event)"/> 
	<mx:RemoteObject id="dataRO" destination="DataDest">
		<mx:method name="GetData" result="GetDataResult(event)" fault="GetDataFault(event)" />
	</mx:RemoteObject>
</fx:Declarations>
<fx:Script>
<![CDATA[
	private function GetDataResult(event:ResultEvent):void {
		var result:String = event.result as String;
		//Ваш код
	}
	private function GetDataFault(event:FaultEvent):void{
		var error:String = ObjectUtil.toString(event.fault);
		//Ваш код
	}
	private function messageHandler(event:MessageEvent):void
	{
		var msg:IMessage = event.message;
		var type:object = msg.body;
		//Ваш код
	}
]]>
</fx:Script>

And the final touch is adding the SendMessage method to our AppAdapter to send messages from the server to the client.

Appadapter.cs
publicclassAppAdapter : MessagingAdapter, ISessionListener
{
    /*
     * ...
    */publicoverrideobjectInvoke(IMessage message)
    {
        //Здесь передается управление вашему коду для обработки пересылки сообщений
        MessageService messageService = this.Destination.Service as MessageService;
        messageService.PushMessageToClients(message);
        returnnull;
    }
    publicstaticvoidSendMessage(string message)
    {
        MessageBroker msgBroker = MessageBroker.GetMessageBroker(null);
        AsyncMessage msg = new AsyncMessage();
        msg.destination = "data_destination";
        msg.headers.Add(AsyncMessage.SubtopicHeader, "client");
        msg.headers.Add(AsyncMessage.EndpointHeader, "my-rtmp");
        msg.headers.Add(AsyncMessage.RemoteCredentialsHeader, string.Empty);
        msg.headers.Add(AsyncMessage.FlexClientIdHeader, Guid.NewGuid().ToString("D"));
        msg.clientId = Guid.NewGuid().ToString("D");
        msg.messageId = Guid.NewGuid().ToString("D");
        msg.timestamp = Environment.TickCount;
        msg.body = message;
        msgBroker.RouteMessage(msg);
    }
}


Afterword

In this post I wanted to reveal the main essence of Flex + ASP.NET binding. Of course, such moments as authentication and authorization, strictly typed server responses, and not just string and much more, were not disclosed. But more about that next time.
All code for Flex and the solution itself with an example for VS 2010 can be downloaded here .

Also popular now: