Skip to content

Commit 835ee60

Browse files
Merge pull request #1 from TsuyoshiUshio/refactoring/tictactoe
Refactoring/tictactoe Done
2 parents 7a61b17 + b60f3a5 commit 835ee60

File tree

7 files changed

+48
-53
lines changed

7 files changed

+48
-53
lines changed

Chapter04/ActorTicTacToeApplication/ActorTicTacToeApplication/ApplicationPackageRoot/ApplicationManifest.xml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<?xml version="1.0" encoding="utf-8"?>
2-
<ApplicationManifest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ApplicationTypeName="ActorTicTacToeApplicationType" ApplicationTypeVersion="1.0.1" xmlns="http://schemas.microsoft.com/2011/01/fabric">
2+
<ApplicationManifest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ApplicationTypeName="ActorTicTacToeApplicationType" ApplicationTypeVersion="1.0.2" xmlns="http://schemas.microsoft.com/2011/01/fabric">
33
<Parameters>
44
<Parameter Name="GameActorService_PartitionCount" DefaultValue="10" />
55
<Parameter Name="GameActorService_MinReplicaSetSize" DefaultValue="3" />
@@ -12,7 +12,7 @@
1212
should match the Name and Version attributes of the ServiceManifest element defined in the
1313
ServiceManifest.xml file. -->
1414
<ServiceManifestImport>
15-
<ServiceManifestRef ServiceManifestName="GamePkg" ServiceManifestVersion="1.0.1" />
15+
<ServiceManifestRef ServiceManifestName="GamePkg" ServiceManifestVersion="1.0.2" />
1616
</ServiceManifestImport>
1717
<ServiceManifestImport>
1818
<ServiceManifestRef ServiceManifestName="PlayerPkg" ServiceManifestVersion="1.0.0" />

Chapter04/ActorTicTacToeApplication/ActorTicTacToeApplication/PublishProfiles/Cloud.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
StoreLocation="CurrentUser"
2929
StoreName="My" />
3030
<ApplicationParameterFile Path="..\ApplicationParameters\Cloud.xml" />
31-
<UpgradeDeployment Mode="Monitored" Enabled="true">
31+
<UpgradeDeployment Mode="Monitored" Enabled="false">
3232
<Parameters FailureAction="Rollback" Force="True" />
3333
</UpgradeDeployment>
3434
</PublishProfile>

Chapter04/ActorTicTacToeApplication/ActorTicTacToeApplication/PublishProfiles/Local.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
-->
99
<ClusterConnectionParameters />
1010
<ApplicationParameterFile Path="..\ApplicationParameters\Local.xml" />
11-
<UpgradeDeployment Mode="UnmonitoredAuto" Enabled="false">
11+
<UpgradeDeployment Mode="UnmonitoredAuto" Enabled="true">
1212
<Parameters UpgradeReplicaSetCheckTimeoutSec="1" Force="True" />
1313
</UpgradeDeployment>
1414
</PublishProfile>
Lines changed: 36 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
11
using System;
22
using System.Collections.Generic;
33
using System.Linq;
4-
using System.Threading;
54
using System.Threading.Tasks;
6-
using Microsoft.ServiceFabric.Actors;
75
using Microsoft.ServiceFabric.Actors.Runtime;
8-
using Microsoft.ServiceFabric.Actors.Client;
96
using Game.Interfaces;
107
using System.Runtime.Serialization;
118
using Microsoft.ServiceFabric.Data;
@@ -24,6 +21,7 @@ namespace Game
2421
[StatePersistence(StatePersistence.Persisted)]
2522
internal class Game : Actor, IGame
2623
{
24+
private static readonly string STATE_KEY = "MyState";
2725
[DataContract]
2826
public class ActorState
2927
{
@@ -43,9 +41,9 @@ public class ActorState
4341
/// This method is called whenever an actor is activated.
4442
/// An actor is activated the first time any of its methods are invoked.
4543
/// </summary>
46-
protected override Task OnActivateAsync()
44+
protected override async Task OnActivateAsync()
4745
{
48-
ConditionalValue<ActorState> state = this.StateManager.TryGetStateAsync<ActorState>("MyState").GetAwaiter().GetResult();
46+
ConditionalValue<ActorState> state = await this.StateManager.TryGetStateAsync<ActorState>(STATE_KEY);
4947
if (!state.HasValue)
5048
{
5149
var actorState = new ActorState()
@@ -56,57 +54,54 @@ protected override Task OnActivateAsync()
5654
NextPlayerIndex = 0,
5755
NumberOfMoves = 0
5856
};
59-
this.StateManager.SetStateAsync<ActorState>("MyState", actorState);
57+
await this.StateManager.SetStateAsync<ActorState>(STATE_KEY, actorState);
6058
}
61-
return Task.FromResult(true);
6259
}
63-
64-
private ActorState State
60+
private async Task<ActorState> GetActorState()
6561
{
66-
get
67-
{
68-
return this.StateManager.TryGetStateAsync<ActorState>("MyState").GetAwaiter().GetResult().Value;
69-
}
70-
71-
set
72-
{
73-
this.StateManager.AddOrUpdateStateAsync<ActorState>("MyState", value, (ke, v) => value);
74-
}
75-
62+
ConditionalValue<ActorState> stateValue = await this.StateManager.TryGetStateAsync<ActorState>(STATE_KEY);
63+
return await Task.FromResult<ActorState>(stateValue.Value);
64+
}
65+
private async Task SetActorState(ActorState state)
66+
{
67+
await this.StateManager.AddOrUpdateStateAsync<ActorState>(STATE_KEY, state, (ke, v) => state);
68+
return;
7669
}
7770

78-
public Task<bool> JoinGameAsync(long playerId, string playerName)
71+
public async Task<bool> JoinGameAsync(long playerId, string playerName)
7972
{
80-
var state = this.State;
81-
if (state.Players.Count >= 2 || state.Players.FirstOrDefault(p => p.Item2 == playerName) != null)
73+
var state = await GetActorState();
74+
if (state.Players.Count >= 2 || state.Players.FirstOrDefault(p => p.Item2 == playerName) != null)
8275
{
83-
return Task.FromResult<bool>(false);
76+
return await Task.FromResult<bool>(false);
8477
}
8578

8679
state.Players.Add(new Tuple<long, string>(playerId, playerName));
87-
this.State = state;
88-
return Task.FromResult<bool>(true);
80+
await SetActorState(state);
81+
return await Task.FromResult<bool>(true);
8982
}
9083

9184
[ReadOnly(true)]
92-
public Task<int[]> GetGameBoardAsync()
85+
public async Task<int[]> GetGameBoardAsync()
9386
{
94-
return Task.FromResult<int[]>(this.State.Board);
87+
var state = await GetActorState();
88+
return await Task.FromResult<int[]>(state.Board);
9589
}
9690
[ReadOnly(true)]
97-
public Task<string> GetWinnerAsync()
91+
public async Task<string> GetWinnerAsync()
9892
{
99-
return Task.FromResult<string>(this.State.Winner);
93+
var state = await GetActorState();
94+
return await Task.FromResult<string>(state.Winner);
10095
}
10196

102-
public Task<bool> MakeMoveAsync(long playerId, int x, int y)
97+
public async Task<bool> MakeMoveAsync(long playerId, int x, int y)
10398
{
104-
var state = this.State;
99+
var state = await GetActorState();
105100
if (x < 0 || x > 2 || y < 0 || y > 2
106101
|| state.Players.Count != 2
107102
|| state.NumberOfMoves >= 9
108103
|| state.Winner != "")
109-
return Task.FromResult<bool>(false);
104+
return await Task.FromResult<bool>(false);
110105

111106
int index = state.Players.FindIndex(p => p.Item1 == playerId);
112107
if (index == state.NextPlayerIndex)
@@ -116,33 +111,34 @@ public Task<bool> MakeMoveAsync(long playerId, int x, int y)
116111
int piece = index * 2 - 1;
117112
state.Board[y * 3 + x] = piece;
118113
state.NumberOfMoves++;
119-
if (HasWon(piece * 3))
114+
if (await HasWonAsync(piece * 3))
120115
state.Winner = state.Players[index].Item2 + " (" +
121116
(piece == -1 ? "X" : "0") + ")";
122117
else if (state.Winner == "" && state.NumberOfMoves >= 9)
123118
state.Winner = "TIE";
124119
state.NextPlayerIndex = (state.NextPlayerIndex + 1) % 2;
125-
this.State = state;
126-
return Task.FromResult<bool>(true);
120+
await SetActorState(state);
121+
return await Task.FromResult<bool>(true);
127122
}
128123
else
129-
return Task.FromResult<bool>(false);
124+
return await Task.FromResult<bool>(false);
130125
}
131126
else
132-
return Task.FromResult<bool>(false);
127+
return await Task.FromResult<bool>(false);
133128
}
134129

135-
private bool HasWon(int sum)
130+
private async Task<bool> HasWonAsync(int sum)
136131
{
137-
var state = this.State;
138-
return state.Board[0] + state.Board[1] + state.Board[2] == sum
132+
var state = await GetActorState();
133+
bool result = state.Board[0] + state.Board[1] + state.Board[2] == sum
139134
|| state.Board[3] + state.Board[4] + state.Board[5] == sum
140135
|| state.Board[6] + state.Board[7] + state.Board[8] == sum
141136
|| state.Board[0] + state.Board[3] + state.Board[6] == sum
142137
|| state.Board[1] + state.Board[4] + state.Board[7] == sum
143138
|| state.Board[2] + state.Board[5] + state.Board[8] == sum
144139
|| state.Board[0] + state.Board[4] + state.Board[8] == sum
145140
|| state.Board[2] + state.Board[4] + state.Board[6] == sum;
141+
return await Task.FromResult<bool>(result);
146142
}
147143
}
148144
}

Chapter04/ActorTicTacToeApplication/Game/PackageRoot/ServiceManifest.xml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<?xml version="1.0" encoding="utf-8"?>
2-
<ServiceManifest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="GamePkg" Version="1.0.1" xmlns="http://schemas.microsoft.com/2011/01/fabric">
2+
<ServiceManifest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="GamePkg" Version="1.0.2" xmlns="http://schemas.microsoft.com/2011/01/fabric">
33
<ServiceTypes>
44
<StatefulServiceType ServiceTypeName="GameActorServiceType" HasPersistedState="true">
55
<Extensions>
@@ -16,7 +16,7 @@
1616
</Extensions>
1717
</StatefulServiceType>
1818
</ServiceTypes>
19-
<CodePackage Name="Code" Version="1.0.1">
19+
<CodePackage Name="Code" Version="1.0.2">
2020
<EntryPoint>
2121
<ExeHost>
2222
<Program>Game.exe</Program>

Chapter06/BadApplication/BadStateful/BadStateful.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using System;
22
using System.Collections.Generic;
33
using System.Fabric;
4-
using System.Linq;
54
using System.Threading;
65
using System.Threading.Tasks;
76
using Microsoft.ServiceFabric.Data.Collections;

Chapter13/SensorAggregationApplication/SensorDataProcessor/SensorDataProcessor.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -43,17 +43,17 @@ protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListe
4343
/// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service replica.</param>
4444
protected override async Task RunAsync(CancellationToken cancellationToken)
4545
{
46-
46+
4747
ServiceEventSource.Current.ServiceMessage(this, "********** Run Async! ******");
48-
DateTime timeStamp = DateTime.Now;
48+
var timeStamp = DateTime.UtcNow;
4949
var proxy = ActorProxy.Create<IIoTHubPartitionMap>(new ActorId(1),
5050
"fabric:/SensorAggregationApplication");
5151
var eventHubClient = EventHubClient.CreateFromConnectionString("HostName=iote2e.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=Bsp4+D5at3lTacsNaZPvx0FhVvrdDa8LGFzKS/B6zzQ=", "messages/events");
5252

5353
while (!cancellationToken.IsCancellationRequested)
5454
{
5555
string partition = await proxy.LeaseTHubPartitionAsync();
56-
timeStamp = DateTime.Now;
56+
timeStamp = DateTime.UtcNow;
5757
if (partition == "")
5858
{
5959
ServiceEventSource.Current.ServiceMessage(this, "********** Partition = '' ******");
@@ -70,16 +70,16 @@ protected override async Task RunAsync(CancellationToken cancellationToken)
7070
if (eventData != null)
7171
{
7272
ServiceEventSource.Current.ServiceMessage(this, "********** the event data is coming! ******");
73-
string data = Encoding.UTF8.GetString(eventData.GetBytes());
73+
var data = Encoding.UTF8.GetString(eventData.GetBytes());
7474
ServiceEventSource.Current.ServiceMessage(this, "Message: {0}", data);
7575

7676
string lease = await proxy.RenewIoTHubPartitionLeaseAsync(partition);
77-
if (DateTime.Now - timeStamp >= TimeSpan.FromSeconds(180)) break;
77+
if (DateTime.UtcNow - timeStamp >= TimeSpan.FromSeconds(180)) break;
7878
}
7979
else
8080
{
8181

82-
if (DateTime.Now - timeStamp > TimeSpan.FromSeconds(20))
82+
if (DateTime.UtcNow - timeStamp > TimeSpan.FromSeconds(20))
8383
{
8484
ServiceEventSource.Current.ServiceMessage(this, "********** break! ******");
8585
break;

0 commit comments

Comments
 (0)