-
Notifications
You must be signed in to change notification settings - Fork 0
/
StoreData.cs
226 lines (182 loc) · 8.55 KB
/
StoreData.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using Microsoft.Azure.Functions.Worker;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System.Diagnostics;
namespace appsvc_fnc_dev_userstats
{
public class StoreData
{
private readonly ILogger<StoreData> _logger;
public StoreData(ILogger<StoreData> logger)
{
_logger = logger;
}
[Function("StoreData")]
// Run everyday at 3am
public async Task Run([TimerTrigger("0 0 3 * * *")] TimerInfo myTimer)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
_logger.LogInformation($"StoreData function received a request at: {DateTime.Now}");
_logger.LogInformation(" ");
var config = new ConfigurationBuilder().AddJsonFile("appsettings.json", true, true).AddEnvironmentVariables().Build();
string connectionString = config["AzureWebJobsStorage"];
//Get UserStats
var userdata = new UserStats();
var usersdata = await userdata.UserStatsDataAsync(_logger);
var ResultUsersStore = await StoreDataUserFile(usersdata, connectionString, "userstats");
_logger.LogInformation(" ");
//Get GroupStats
var groupdata = new GroupStats();
var groupsdata = await groupdata.GroupStatsDataAsync(_logger);
var ResultGroupsStore = await StoreDataGroupFile(groupsdata, connectionString, "groupstats");
_logger.LogInformation(" ");
//Get ActiveUsers
var activeuserdata = new ActiveUsers(usersdata, _logger);
var activeusersdata = await activeuserdata.GetActiveUserCount();
var ResultAcvtiveUsersStore = await StoreDataActiveUsersFile(activeusersdata, connectionString, "activeusers");
_logger.LogInformation(" ");
_logger.LogInformation($"StoreData function processed a request at: {DateTime.Now}");
stopwatch.Stop();
_logger.LogInformation($"Elapsed time: {stopwatch.Elapsed}");
}
public async Task<bool> StoreDataUserFile(List<usersData> usersdata, string connectionString, string containerName)
{
try
{
await CreateContainerIfNotExists(connectionString, containerName);
// CreateFileTitle with date
DateTime now = DateTime.Now;
string FileTitle = now.ToString("dd-MM-yyyy") + "-" + containerName + ".json";
_logger.LogInformation($"FileTitle: {FileTitle}");
// Create file with userData
BlobClient blobClient = new BlobClient(connectionString, containerName, FileTitle);
List<usersData> listUsersData = new List<usersData>();
foreach (var user in usersdata)
{
listUsersData.Add(new usersData()
{
Id = user.Id,
creationDate = user.creationDate,
mail = user.mail
});
}
string json = JsonConvert.SerializeObject(listUsersData.ToArray());
using (MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
{
LoadStreamWithJson(ms, json);
await blobClient.UploadAsync(ms, true); // overwrite existing = true
}
BlobHttpHeaders headers = new BlobHttpHeaders();
headers.ContentType = "application/json";
await blobClient.SetHttpHeadersAsync(headers);
_logger.LogInformation($"Blob {FileTitle} is uploaded to container: {containerName}");
return true;
}
catch (Exception e)
{
_logger.LogError("!! Exception !!");
_logger.LogError(e.Message);
_logger.LogError("!! StackTrace !!");
_logger.LogError(e.StackTrace);
return false;
}
}
public async Task<bool> StoreDataGroupFile(List<SingleGroup> groupsdata, string connectionString, string containerName)
{
try
{
await CreateContainerIfNotExists(connectionString, containerName);
//CreateFileTitle with date
DateTime now = DateTime.Now;
string FileTitle = now.ToString("dd-MM-yyyy") + "-" + containerName + ".json";
BlobClient blobClient = new BlobClient(connectionString, containerName, FileTitle);
//Create file with userData
List<groupsData> listGroupsData = new List<groupsData>();
foreach (var group in groupsdata)
{
listGroupsData.Add(new groupsData()
{
displayName = group.displayName,
countMember = group.countMember,
groupId = group.groupId,
creationDate = group.creationDate,
description = group.description,
groupType = group.groupType,
userlist = group.userlist
});
}
string json = JsonConvert.SerializeObject(listGroupsData.ToArray());
using (var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
{
LoadStreamWithJson(ms, json);
await blobClient.UploadAsync(ms, true); // overwrite existing = true
}
BlobHttpHeaders headers = new BlobHttpHeaders();
headers.ContentType = "application/json";
await blobClient.SetHttpHeadersAsync(headers);
_logger.LogInformation($"Blob {FileTitle} is uploaded to container: {containerName}");
return true;
}
catch (Exception e)
{
_logger.LogError("!! Exception !!");
_logger.LogError(e.Message);
_logger.LogError("!! StackTrace !!");
_logger.LogError(e.StackTrace);
return false;
}
}
public async Task<bool> StoreDataActiveUsersFile(List<countactiveuserData> activeusersdata, string connectionString, string containerName)
{
try
{
await CreateContainerIfNotExists(connectionString, containerName);
// Create file title with date
DateTime now = DateTime.Now;
string FileTitle = now.ToString("dd-MM-yyyy") + "-" + containerName + ".json";
// Create file with activeusersdata
BlobClient blobClient = new BlobClient(connectionString, containerName, FileTitle);
string json = JsonConvert.SerializeObject(activeusersdata.ToArray());
using (var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
{
LoadStreamWithJson(ms, json);
await blobClient.UploadAsync(ms, true); // overwrite existing = true
}
BlobHttpHeaders headers = new BlobHttpHeaders();
headers.ContentType = "application/json";
await blobClient.SetHttpHeadersAsync(headers);
_logger.LogInformation($"Blob {FileTitle} is uploaded to container: {containerName}");
return true;
}
catch (Exception e)
{
_logger.LogError("!! Exception !!");
_logger.LogError(e.Message);
_logger.LogError("!! StackTrace !!");
_logger.LogError(e.StackTrace);
return false;
}
}
public async Task CreateContainerIfNotExists(string connectionString, string containerName)
{
_logger.LogInformation($"Create container check: {containerName}");
BlobContainerClient container = new BlobContainerClient(connectionString, containerName);
await container.CreateIfNotExistsAsync();
_logger.LogInformation($"Container check complete.");
}
private void LoadStreamWithJson(Stream ms, string obj)
{
StreamWriter writer = new StreamWriter(ms);
writer.Write(obj);
ms.Position = 0;
}
}
}