📜 ⬆️ ⬇️

How to make a sea battle online on Silverlight 4 (detailed article)

Good day! This text is a detailed article about how I did a naval battle at Silverlight 4. I was inspired to write an article with your comments. Source codes can be found here . Test login test@mail.ru, password 123456. But there is a restriction on the fact that players must have different logins. Therefore, one person must be registered, otherwise there will be an error that will be fixed soon.
image

So, I am a certified specialist in various fields, but according to WPF (what Silverligh is based on) I had 0. So I decided to study the basics of this technology based on a living example, which the sea battle known from childhood became. Taking into account the above, this article does not describe the optimal mechanisms for the use of technology, because, for sure, there is a more elegant solution.
In general, we will need: Visual studio 2010 (I have the Ultimate version, but I think you can try it on the free Visual Web Developer 2010 Express version), and you also need to install Silverlight 4 tools for VS 2010 . After everything has been downloaded and installed, you can get down to business! First we need to create a host application in ASP.NET (File-New Project - Web Application). I have already created it in advance, and Membership (MS SQL) has to be configured there. Read more about it here . The main element of the membership will be the table from the Users database, since it relies on the logic of working with users. You should also add that profiles are used. To configure them, insert the following lines into web.config:
profile element enabled = "true" defaultProvider = "SqlProfileProvider", add an element to the properties sub-element
add name = "NickName".

Now everything is ready to create silverlight application! We go to the File-AddNewProject, select the Silverlight Application, specify our host application, and also tick the future: Net RIA Services. So, our application is ready. When creating, a test page for launching the silverlight program will automatically appear in the hosting application. Adjust the parameters for running the application and add the following <asp: Literal ID = "LiteralParams" runat = "server"> </ asp: Literal> element to the object element. Such a literal will serve as parameters to which we will pass the address of our web service (since for local testing it is one, and on the hosting it will be completely different):
StringBuilder SB = new StringBuilder();
SB.Append(". param name=\"InitParams\" value=\"");

SB.Append("SFServiceUrl="+GetServiceUrl());

SB.Append("\" /.");

LiteralParams.Text = SB.ToString();


Then we will read these parameters already in the silverlight program:
private void Application_Startup(object sender, StartupEventArgs e)
{
//
ServiceUrl = e.InitParams["SFServiceUrl"];


So, it is more logical to tell about the internal kitchen of the program. We will need to create 5 tables in the database:
image
It is not necessary to establish links, because in our core, they are not yet explicitly used. Cropped strips go to the Users table, the UserId field. Then you will need to create a data context (Linq To SQl) and add these tables to it. In the future, the data context will have the name of the SDC class. It should be placed in a separate assembly (say, SDataAccess). How to do this, I will not describe, because This is the topic of a separate article. Apparently, in order to use Domain services, it is better to make a data context based on LinqTo Entities, but I decided to do it the old-fashioned way.
As a core, I use the Workflow activity library (SWorkflows):
image
')
In it we create the Activities / SeaFight folder. Its contents are in the source. There, the basic logic of the game is sewn up, such as: creating, completing, checking moves, getting data about players, leading a chat, working with the coordinates of ships, etc. In more detail you can familiarize with classes in source codes which lie in the folder Activities \ SeaFight. Linq to Sql queries are used there, and query results are returned via the Workflow service to our Silverlight application.
After our assembly with activities is successfully compiled, you can safely begin to create a Workflow service. To do this in our host application, create it: File-Add New Item - Workflow Service:
image
Then you need to open this XAMLX file and start creating the service. Unlike Workflow from .Net 3.5, authoring Workflow-first is used here, which simplifies the task of creating an interface. Previously, it was necessary to first create an interface with the attributes ServiceContract, OperationContract, etc., and then use it to create a workflow, and now this interface is generated automatically on the basis of workflow. So, in order for our service to be able to process several operations at once within a single Workflow, we need to insert the Peek Activity into the root, and then add to it sequentially into separate Branch (branches) Receive Activity and Receive-Send Activity. Inside the Receive Activity you need to embed our activities, which we did in a separate assembly. They will be automatically available in the Toolbox tab:
image
Now, sequentially creating separate branches, it is necessary to place the activity on Workflow. Next, add the variables for the required activities (in the bottom left of the variables tab), and then link all this (for more details, see the source code - SeaFightService.xamlx). In Receive activity, you must specify the interface (ServiceContractName) and the name of the operation, and also bind the input parameters to variables. Do not forget to put the CanCreateInstance checkbox for each Receive Activity. Read more about this on the workflow website.
Here's how it happened with me:
image
Now that our business logic is ready to play, we add the Service Reference to our Silverlight project (Add Service reference, then select Discover):
image
Now it only remains to make our game interface and use business logic by calling a proxy object. Here's how I used the proxy object:
var proxy = ProxyReference.GetProxy();
try
{
proxy.GetGameListCompleted += new EventHandler . GetGameListCompletedEventArgs . (proxy_GetGameListCompleted);
proxy.GetGameListAsync(proxy);
}
catch
{
proxy.Abort();
}



And here is the method that processes the WCF service response:

//
void proxy_GetGameListCompleted(object sender, GetGameListCompletedEventArgs e)
{
var games = e.Result;
dataGridGames.ItemsSource = games;
((SeaFightServiceClient)e.UserState).CloseAsync();
}



The project has 5 windows: a game creation window, a second player's waiting window, a ship placement window, a battle window and a results window. Accordingly, they are all in the source code, and you can get acquainted with their composition in more detail. As a playing field, I used a standard component - the Grid, and the positions of the ships are marked with standard ToggleButton with a modified Content property. Again, to find out how everything is done in detail, see the source code of the project SeaFight.
To switch windows, use the PageSwitcher element, which stores the current window in its Content root property. To switch between windows, I use the following code:

if (this.Parent is PageSwitcher)
{
PageSwitcher ps = this.Parent as PageSwitcher;
ps.Navigate(new MainPage());
}


One of the major drawbacks of the project is the lack of duplex mode in the network service. Therefore, the System.Windows.Threading.DispatcherTimer timer is used to update the state. Because of this, there is a delay between the receipt of messages and the moves in the game. In the future, it is still planned to switch to duplex mode, but this is not an easy task for Silverlight. This is how the ship placement window looks like:
image

I would like to note that there is 1 more auxiliary project: SEntities, which contains general classes for the kernel and silverlight applications. It is more correct for the future to use a special type of assembly - Silverlight Library, and not the usual Library, which is now.
In general, this is the end of this article, as the main points are described by me, and the description of individual functions can take one more article for each function. Therefore, for more detailed details (how to make the placement of elements on the form, etc., you can contact MSDN or me). If you want to help in the development of this project - write: squalsoft {at} mail.ru.

Source: https://habr.com/ru/post/95054/


All Articles