/
ViewPageBase.cs
464 lines (383 loc) · 12.8 KB
/
ViewPageBase.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using ServiceStack.CacheAccess;
using ServiceStack.Common.Web;
using ServiceStack.Html;
using ServiceStack.Messaging;
using ServiceStack.MiniProfiler;
using ServiceStack.OrmLite;
using ServiceStack.Redis;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface;
using ServiceStack.ServiceInterface.Auth;
using ServiceStack.ServiceInterface.ServiceModel;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints;
using IHtmlString = System.Web.IHtmlString;
namespace ServiceStack.Razor
{
/// <summary>
/// Class to represent attribute values and, more importantly,
/// decipher them from tuple madness slightly.
/// </summary>
public class AttributeValue
{
public Tuple<string, int> Prefix { get; private set; }
public Tuple<object, int> Value { get; private set; }
public bool IsLiteral { get; private set; }
public AttributeValue(Tuple<string, int> prefix, Tuple<object, int> value, bool isLiteral)
{
this.Prefix = prefix;
this.Value = value;
this.IsLiteral = isLiteral;
}
public static implicit operator AttributeValue(Tuple<Tuple<string, int>, Tuple<object, int>, bool> value)
{
return new AttributeValue(value.Item1, value.Item2, value.Item3);
}
public static implicit operator AttributeValue(Tuple<Tuple<string, int>, Tuple<string, int>, bool> value)
{
return new AttributeValue(
value.Item1, new Tuple<object, int>(value.Item2.Item1, value.Item2.Item2), value.Item3);
}
}
//Should handle all razor rendering functionality
public abstract class RenderingPage
{
public IHttpRequest Request { get; set; }
public IHttpResponse Response { get; set; }
public StreamWriter Output { get; set; }
public dynamic ViewBag { get; set; }
public IViewBag TypedViewBag
{
get { return (IViewBag)ViewBag; }
}
public IRazorView ParentPage { get; set; }
public IRazorView ChildPage { get; set; }
public string ChildBody { get; set; }
public Dictionary<string, Action> childSections = new Dictionary<string, Action>();
protected RenderingPage()
{
this.ViewBag = new DynamicDictionary(this);
}
//overridden by the RazorEngine when razor generates code.
public abstract void Execute();
//No HTML encoding
public virtual void WriteLiteral(string str)
{
this.Output.Write(str);
}
//With HTML encoding
public virtual void Write(object obj)
{
this.Output.Write(HtmlEncode(obj));
}
//With HTML encoding
public virtual void WriteTo(TextWriter writer, HelperResult value)
{
if (value != null)
{
value.WriteTo(writer);
}
}
public virtual void WriteLiteralTo(TextWriter writer, HelperResult value)
{
if (value != null)
{
value.WriteTo(writer);
}
}
public void WriteLiteralTo(TextWriter writer, string literal)
{
if (literal == null)
return;
writer.Write(literal);
}
private static string HtmlEncode(object value)
{
if (value == null)
{
return null;
}
var str = value as System.Web.IHtmlString;
return str != null ? str.ToHtmlString() : HttpUtility.HtmlEncode(Convert.ToString(value, CultureInfo.CurrentCulture));
}
public virtual void WriteAttribute(string name, Tuple<string, int> prefix, Tuple<string, int> suffix, params AttributeValue[] values)
{
var attributeValue = this.BuildAttribute(name, prefix, suffix, values);
this.WriteLiteral(attributeValue);
}
public virtual void WriteAttributeTo(TextWriter writer, string name, Tuple<string, int> prefix, Tuple<string, int> suffix, params AttributeValue[] values)
{
var attributeValue = this.BuildAttribute(name, prefix, suffix, values);
WriteLiteralTo(writer, attributeValue);
}
private string BuildAttribute(string name, Tuple<string, int> prefix, Tuple<string, int> suffix,
params AttributeValue[] values)
{
var writtenAttribute = false;
var attributeBuilder = new StringBuilder(prefix.Item1);
foreach (var value in values)
{
if (this.ShouldWriteValue(value.Value.Item1))
{
var stringValue = this.GetStringValue(value);
var valuePrefix = value.Prefix.Item1;
if (!string.IsNullOrEmpty(valuePrefix))
{
attributeBuilder.Append(valuePrefix);
}
attributeBuilder.Append(stringValue);
writtenAttribute = true;
}
}
attributeBuilder.Append(suffix.Item1);
var renderAttribute = writtenAttribute || values.Length == 0;
if (renderAttribute)
{
return attributeBuilder.ToString();
}
return string.Empty;
}
private string GetStringValue(AttributeValue value)
{
if (value.IsLiteral)
{
return (string)value.Value.Item1;
}
var htmlString = value.Value.Item1 as IHtmlString;
if (htmlString != null)
return htmlString.ToHtmlString();
//if (value.Value.Item1 is DynamicDictionaryValue) {
// var dynamicValue = (DynamicDictionaryValue)value.Value.Item1;
// return dynamicValue.HasValue ? dynamicValue.Value.ToString() : string.Empty;
//}
return value.Value.Item1.ToString();
}
private bool ShouldWriteValue(object value)
{
if (value == null)
{
return false;
}
if (value is bool)
{
var boolValue = (bool)value;
return boolValue;
}
return true;
}
public void SetChildPage(IRazorView childPage, string childBody)
{
this.ChildPage = childPage;
this.ChildBody = childBody;
}
public object RenderBody()
{
if (ChildBody != null)
{
Output.Write(ChildBody);
}
return null;
}
public virtual bool IsSectionDefined(string sectionName)
{
return this.childSections.ContainsKey(sectionName);
}
public virtual void DefineSection(string sectionName, Action action)
{
this.childSections.Add(sectionName, action);
}
public object RenderSection(string sectionName, bool required)
{
if (required && !IsSectionDefined(sectionName) && !ChildPage.IsSectionDefined(sectionName))
throw new Exception("Required Section {0} is not defined".Fmt(sectionName));
return RenderSection(sectionName);
}
public object RenderSection(string sectionName)
{
Action section;
if (childSections.TryGetValue(sectionName, out section))
{
section();
}
else if (this.ChildPage != null)
{
this.ChildPage.RenderSection(sectionName, Output);
}
return null;
}
public void RenderSection(string sectionName, StreamWriter writer)
{
Action section;
if (childSections.TryGetValue(sectionName, out section))
{
var hold = Output;
try
{
Output = writer;
section();
Output.Flush();
}
finally
{
Output = hold;
}
}
}
}
public interface IHasModel
{
Type ModelType { get; }
void SetModel(object o);
}
public abstract class ViewPageBase<TModel> : RenderingPage, IHasModel where TModel : class
{
public string Layout
{
get
{
return layout;
}
set
{
layout = value != null ? value.Trim(' ', '"') : null;
}
}
public TModel Model { get; set; }
public abstract Type ModelType { get; }
public virtual void SetModel(object o)
{
var viewModel = o as TModel;
this.Model = viewModel;
if (viewModel == null)
{
this.ModelError = o;
}
}
public UrlHelper Url = new UrlHelper();
private IAppHost appHost;
public virtual IViewEngine ViewEngine { get; set; }
public IAppHost AppHost
{
get { return appHost ?? EndpointHost.AppHost; }
set { appHost = value; }
}
public T Get<T>()
{
return this.AppHost.TryResolve<T>();
}
public object ModelError { get; set; }
public ResponseStatus ResponseStatus
{
get
{
return ToResponseStatus(ModelError) ?? ToResponseStatus(Model);
}
}
private ResponseStatus ToResponseStatus<T>(T modelError)
{
var ret = modelError.ToResponseStatus();
if (ret != null) return ret;
if (modelError is DynamicObject)
{
var dynError = modelError as dynamic;
return (ResponseStatus)dynError.ResponseStatus;
}
return null;
}
private ICacheClient cache;
public ICacheClient Cache
{
get { return cache ?? (cache = Get<ICacheClient>()); }
}
private IDbConnection db;
public IDbConnection Db
{
get { return db ?? (db = Get<IDbConnectionFactory>().OpenDbConnection()); }
}
private IRedisClient redis;
public IRedisClient Redis
{
get { return redis ?? (redis = Get<IRedisClientsManager>().GetClient()); }
}
private IMessageProducer messageProducer;
public virtual IMessageProducer MessageProducer
{
get { return messageProducer ?? (messageProducer = Get<IMessageFactory>().CreateMessageProducer()); }
}
private ISessionFactory sessionFactory;
private ISession session;
public virtual ISession Session
{
get
{
if (sessionFactory == null)
sessionFactory = new SessionFactory(Cache);
return session ?? (session = sessionFactory.GetOrCreateSession(Request, Response));
}
}
private IAuthSession userSession;
private string layout;
public virtual T GetSession<T>() where T : class, IAuthSession
{
if (userSession != null) return (T)userSession;
return (T)(userSession = SessionFeature.GetOrCreateSession<T>(Cache, Request, Response));
}
public string SessionKey
{
get
{
return SessionFeature.GetSessionKey();
}
}
public void ClearSession()
{
userSession = null;
this.Cache.Remove(SessionKey);
}
public virtual void Dispose()
{
try
{
if (cache != null) cache.Dispose();
cache = null;
}
catch { }
try
{
if (db != null) db.Dispose();
db = null;
}
catch { }
try
{
if (redis != null) redis.Dispose();
redis = null;
}
catch { }
try
{
if (messageProducer != null) messageProducer.Dispose();
messageProducer = null;
}
catch { }
}
public string Href(string url)
{
var replacedUrl = Url.Content(url);
return replacedUrl;
}
public void Prepend(string contents)
{
if (contents == null) return;
//Builder.Insert(0, contents);
}
}
}