-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHomeController.cs
114 lines (105 loc) · 3.91 KB
/
HomeController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
using Alachisoft.NCache.Web.SessionState;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
namespace SessionCaching.Controllers
{
// code taken from: https://github.com/Alachisoft/NCache-Samples/blob/master/dotnetcore/SessionCaching/GuessGame/src/Controllers/GuessGameController.cs
public class HomeController : Controller
{
private const string SecretNumber = "SecretNumber";
private const string History = "History";
private const string LastValue = "LastValue";
private const string Victory = "YouWin";
private const string IsGreater = "IsGreater";
private const string StartNewGameKey = "StartNewGame";
// GET: /<controller>/
public IActionResult Index()
{
HttpContext.Session.TryGetValue(StartNewGameKey, out object newGame);
if (newGame == null || newGame.Equals("true"))
{
HttpContext.Session.Set(StartNewGameKey, "false");
}
StartNewGame();
return View();
}
public IActionResult Guess(string id)
{
ViewData[Victory] = false;
if (id != null)
{
object history = null;
if (HttpContext.Session.TryGetValue(History, out history))
{
ViewData[History] = history;
object number;
HttpContext.Session.TryGetValue(SecretNumber, out number);
if (number != null)
{
ViewData[SecretNumber] = number;
int guessedNumber;
if (int.TryParse(id, out guessedNumber))
{
if (((int)number).Equals(guessedNumber))
{
HttpContext.Session.Set(StartNewGameKey, "true");
ViewData[Victory] = true;
}
else
{
if (guessedNumber > ((int)number))
{
ViewData[IsGreater] = true;
}
else
{
ViewData[IsGreater] = false;
}
}
var list = history as List<int>;
list?.Add(guessedNumber);
ViewData[LastValue] = guessedNumber;
}
}
HttpContext.Session.Set(History, history);
}
else
{
return NewGame();
}
}
return View("Index");
}
public IActionResult NewGame()
{
HttpContext.Session.Clear();
StartNewGame();
return View("Index");
}
private void StartNewGame()
{
object number;
HttpContext.Session.TryGetValue(SecretNumber, out number);
if (number == null)
{ number = new Random(DateTime.Now.Millisecond).Next(0, 100); }
ViewData[SecretNumber] = number;
HttpContext.Session.Set(SecretNumber, number);
object history;
if (HttpContext.Session.TryGetValue(History, out history))
{
var list = history as List<int>;
if (list.Count > 0)
{
ViewData[History] = list;
ViewData[LastValue] = list[list.Count - 1];
}
}
else
{
history = new List<int>();
HttpContext.Session.Set(History, history);
}
}
}
}