/
library.cs
1996 lines (1807 loc) · 80.6 KB
/
library.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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Xml;
using System.Xml.XPath;
using Newtonsoft.Json;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Logging;
using Umbraco.Web;
using Umbraco.Web.Cache;
using Umbraco.Web.Templates;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.media;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.propertytype;
using umbraco.cms.businesslogic.relation;
using umbraco.cms.businesslogic.web;
using umbraco.cms.helpers;
using umbraco.scripting;
using umbraco.DataLayer;
using umbraco.cms.businesslogic.language;
using Umbraco.Core.IO;
using UmbracoContext = umbraco.presentation.UmbracoContext;
namespace umbraco
{
/// <summary>
/// Function library for umbraco. Includes various helper-methods and methods to
/// save and load data from umbraco.
///
/// Especially usefull in XSLT where any of these methods can be accesed using the umbraco.library name-space. Example:
/// <xsl:value-of select="umbraco.library:NiceUrl(@id)"/>
/// </summary>
public class library
{
/// <summary>
/// Returns a new UmbracoHelper so that we can start moving the logic from some of these methods to it
/// </summary>
/// <returns></returns>
private static UmbracoHelper GetUmbracoHelper()
{
return new UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
}
#region Declarations
/// <summary>
/// Used by umbraco's publishing enginge, to determine if publishing is currently active
/// </summary>
public static bool IsPublishing = false;
/// <summary>
/// Used by umbraco's publishing enginge, to how many nodes is publish in the current publishing cycle
/// </summary>
public static int NodesPublished = 0;
/// <summary>
/// Used by umbraco's publishing enginge, to determine the start time of the current publishing cycle.
/// </summary>
public static DateTime PublishStart;
private page _page;
private static readonly object libraryCacheLock = new object();
#endregion
#region Properties
protected static ISqlHelper SqlHelper
{
get { return umbraco.BusinessLogic.Application.SqlHelper; }
}
#endregion
#region Constructors
/// <summary>
/// Empty constructor
/// </summary>
public library()
{
}
public library(int id)
{
_page = new page(((System.Xml.IHasXmlNode)GetXmlNodeById(id.ToString()).Current).GetNode());
}
/// <summary>
/// Initializes a new instance of the <see cref="library"/> class.
/// </summary>
/// <param name="Page">The page.</param>
public library(page page)
{
_page = page;
}
#endregion
#region Python Helper functions
/// <summary>
/// Executes the given python script and returns the standardoutput.
/// The Globals known from python macros are not accessible in this context.
/// Neither macro or page nor the globals known from python macros are
/// accessible in this context. Only stuff we initialized in site.py
/// can be used.
/// </summary>
/// <param name="file">The filename of the python script including the extension .py</param>
/// <returns>Returns the StandardOutput</returns>
public static string PythonExecuteFile(string file)
{
try
{
string path = IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + file);
object res = python.executeFile(path);
return res.ToString();
}
catch (Exception e)
{
return e.Message;
}
}
/// <summary>
/// Executes the given python expression and returns the standardoutput.
/// The Globals known from python macros are not accessible in this context.
/// Neighter macro or page nor the globals known from python macros are
/// accessible in this context. Only stuff we initialized in site.py
/// can be used.
/// </summary>
/// <param name="expression">Python expression to execute</param>
/// <returns>Returns the StandardOutput</returns>
public static string PythonExecute(string expression)
{
try
{
object res = python.execute(expression);
return res.ToString();
}
catch (Exception e)
{
return e.Message;
}
}
#endregion
#region Publish Helper Methods
/// <summary>
/// Unpublish a node, by removing it from the runtime xml index. Note, prior to this the Document should be
/// marked unpublished by setting the publish property on the document object to false
/// </summary>
/// <param name="DocumentId">The Id of the Document to be unpublished</param>
[Obsolete("This method is no longer used, a document's cache will be removed automatically when the document is deleted or unpublished")]
public static void UnPublishSingleNode(int DocumentId)
{
DistributedCache.Instance.RemovePageCache(DocumentId);
}
/// <summary>
/// Publishes a Document by adding it to the runtime xml index. Note, prior to this the Document should be
/// marked published by calling Publish(User u) on the document object.
/// </summary>
/// <param name="documentId">The Id of the Document to be published</param>
[Obsolete("This method is no longer used, a document's cache will be updated automatically when the document is published")]
public static void UpdateDocumentCache(int documentId)
{
DistributedCache.Instance.RefreshPageCache(documentId);
}
/// <summary>
/// Publishes the single node, this method is obsolete
/// </summary>
/// <param name="DocumentId">The document id.</param>
[Obsolete("Please use: umbraco.library.UpdateDocumentCache")]
public static void PublishSingleNode(int DocumentId)
{
UpdateDocumentCache(DocumentId);
}
/// <summary>
/// Refreshes the xml cache for all nodes
/// </summary>
public static void RefreshContent()
{
DistributedCache.Instance.RefreshAllPageCache();
}
/// <summary>
/// Re-publishes all nodes under a given node
/// </summary>
/// <param name="nodeID">The ID of the node and childnodes that should be republished</param>
[Obsolete("Please use: umbraco.library.RefreshContent")]
public static string RePublishNodes(int nodeID)
{
DistributedCache.Instance.RefreshAllPageCache();
return string.Empty;
}
/// <summary>
/// Re-publishes all nodes under a given node
/// </summary>
/// <param name="nodeID">The ID of the node and childnodes that should be republished</param>
[Obsolete("Please use: umbraco.library.RefreshContent")]
public static void RePublishNodesDotNet(int nodeID)
{
DistributedCache.Instance.RefreshAllPageCache();
}
/// <summary>
/// Refreshes the runtime xml index.
/// Note: This *doesn't* mark any non-published document objects as published
/// </summary>
/// <param name="nodeID">Always use -1</param>
/// <param name="SaveToDisk">Not used</param>
[Obsolete("Please use: content.Instance.RefreshContentFromDatabaseAsync")]
public static void RePublishNodesDotNet(int nodeID, bool SaveToDisk)
{
DistributedCache.Instance.RefreshAllPageCache();
}
#endregion
#region Xslt Helper functions
/// <summary>
/// This will convert a json structure to xml for use in xslt
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static XPathNodeIterator JsonToXml(string json)
{
try
{
if (json.StartsWith("["))
{
//we'll assume it's an array, in which case we need to add a root
json = "{\"arrayitem\":" + json + "}";
}
var xml = JsonConvert.DeserializeXmlNode(json, "json", false);
return xml.CreateNavigator().Select("/json");
}
catch (Exception ex)
{
var xd = new XmlDocument();
xd.LoadXml(string.Format("<error>Could not convert JSON to XML. Error: {0}</error>", ex));
return xd.CreateNavigator().Select("/error");
}
}
/// <summary>
/// Add a session variable to the current user
/// </summary>
/// <param name="key">The Key of the variable</param>
/// <param name="value">The Value</param>
public static void setSession(string key, string value)
{
if (HttpContext.Current.Session != null)
HttpContext.Current.Session[key] = value;
}
/// <summary>
/// Add a cookie variable to the current user
/// </summary>
/// <param name="key">The Key of the variable</param>
/// <param name="value">The Value of the variable</param>
public static void setCookie(string key, string value)
{
StateHelper.SetCookieValue(key, value);
}
/// <summary>
/// Returns a string with a friendly url from a node.
/// IE.: Instead of having /482 (id) as an url, you can have
/// /screenshots/developer/macros (spoken url)
/// </summary>
/// <param name="nodeID">Identifier for the node that should be returned</param>
/// <returns>String with a friendly url from a node</returns>
public static string NiceUrl(int nodeID)
{
return GetUmbracoHelper().NiceUrl(nodeID);
}
/// <summary>
/// This method will always add the root node to the path. You should always use NiceUrl, as that is the
/// only one who checks for toplevel node settings in the web.config
/// </summary>
/// <param name="nodeID">Identifier for the node that should be returned</param>
/// <returns>String with a friendly url from a node</returns>
[Obsolete]
public static string NiceUrlFullPath(int nodeID)
{
throw new NotImplementedException("It was broken anyway...");
}
/// <summary>
/// This method will always add the domain to the path if the hostnames are set up correctly.
/// </summary>
/// <param name="nodeID">Identifier for the node that should be returned</param>
/// <returns>String with a friendly url with full domain from a node</returns>
public static string NiceUrlWithDomain(int nodeID)
{
return GetUmbracoHelper().NiceUrlWithDomain(nodeID);
}
/// <summary>
/// This method will always add the domain to the path.
/// </summary>
/// <param name="nodeID">Identifier for the node that should be returned</param>
/// <param name="ignoreUmbracoHostNames">Ignores the umbraco hostnames and returns the url prefixed with the requested host (including scheme and port number)</param>
/// <returns>String with a friendly url with full domain from a node</returns>
internal static string NiceUrlWithDomain(int nodeID, bool ignoreUmbracoHostNames)
{
if (ignoreUmbracoHostNames)
return HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + NiceUrl(nodeID);
return NiceUrlWithDomain(nodeID);
}
public static string ResolveVirtualPath(string path)
{
return Umbraco.Core.IO.IOHelper.ResolveUrl(path);
}
/// <summary>
/// Returns a string with the data from the given element of a node. Both elements (data-fields)
/// and properties can be used - ie:
/// getItem(1, nodeName) will return a string with the name of the node with id=1 even though
/// nodeName is a property and not an element (data-field).
/// </summary>
/// <param name="nodeID">Identifier for the node that should be returned</param>
/// <param name="alias">The element that should be returned</param>
/// <returns>Returns a string with the data from the given element of a node</returns>
public static string GetItem(int nodeID, String alias)
{
var doc = Umbraco.Web.UmbracoContext.Current.ContentCache.GetById(nodeID);
if (doc == null)
return string.Empty;
switch (alias)
{
case "id":
return doc.Id.ToString();
case "version":
return doc.Version.ToString();
case "parentID":
return doc.Parent.Id.ToString();
case "level":
return doc.Level.ToString();
case "writerID":
return doc.WriterId.ToString();
case "template":
return doc.TemplateId.ToString();
case "sortOrder":
return doc.SortOrder.ToString();
case "createDate":
return doc.CreateDate.ToString("yyyy-MM-dd'T'HH:mm:ss");
case "updateDate":
return doc.UpdateDate.ToString("yyyy-MM-dd'T'HH:mm:ss");
case "nodeName":
return doc.Name;
case "writerName":
return doc.WriterName;
case "path":
return doc.Path;
case "creatorName":
return doc.CreatorName;
}
// in 4.9.0 the method returned the raw XML from the cache, unparsed
// starting with 5c20f4f (4.10?) the method returns prop.Value.ToString()
// where prop.Value is parsed for internal links + resolve urls - but not for macros
// comments say "fixing U4-917 and U4-821" which are not related
// if we return DataValue.ToString() we're back to the original situation
// if we return Value.ToString() we'll have macros parsed and that's nice
//
// so, use Value.ToString() here.
var prop = doc.GetProperty(alias);
return prop == null ? string.Empty : prop.Value.ToString();
}
/// <summary>
/// Checks with the Assigned domains settings and retuns an array the the Domains matching the node
/// </summary>
/// <param name="NodeId">Identifier for the node that should be returned</param>
/// <returns>A Domain array with all the Domains that matches the nodeId</returns>
public static Domain[] GetCurrentDomains(int NodeId)
{
string[] pathIds = GetItem(NodeId, "path").Split(',');
for (int i = pathIds.Length - 1; i > 0; i--)
{
Domain[] retVal = Domain.GetDomainsById(int.Parse(pathIds[i]));
if (retVal.Length > 0)
{
return retVal;
}
}
return null;
}
/// <summary>
/// Returns a string with the data from the given element of the current node. Both elements (data-fields)
/// and properties can be used - ie:
/// getItem(nodeName) will return a string with the name of the current node/page even though
/// nodeName is a property and not an element (data-field).
/// </summary>
/// <param name="alias"></param>
/// <returns></returns>
public static string GetItem(String alias)
{
try
{
int currentID = int.Parse(HttpContext.Current.Items["pageID"].ToString());
return GetItem(currentID, alias);
}
catch (Exception ItemException)
{
HttpContext.Current.Trace.Warn("library.GetItem", "Error reading '" + alias + "'", ItemException);
return string.Empty;
}
}
/// <summary>
/// Returns that name of a generic property
/// </summary>
/// <param name="ContentTypeAlias">The Alias of the content type (ie. Document Type, Member Type or Media Type)</param>
/// <param name="PropertyTypeAlias">The Alias of the Generic property (ie. bodyText or umbracoNaviHide)</param>
/// <returns>A string with the name. If nothing matches the alias, an empty string is returned</returns>
public static string GetPropertyTypeName(string ContentTypeAlias, string PropertyTypeAlias)
{
try
{
umbraco.cms.businesslogic.ContentType ct = umbraco.cms.businesslogic.ContentType.GetByAlias(ContentTypeAlias);
PropertyType pt = ct.getPropertyType(PropertyTypeAlias);
return pt.Name;
}
catch
{
return string.Empty;
}
}
/// <summary>
/// Returns the Member Name from an umbraco member object
/// </summary>
/// <param name="MemberId">The identifier of the Member</param>
/// <returns>The Member name matching the MemberId, an empty string is member isn't found</returns>
public static string GetMemberName(int MemberId)
{
if (MemberId != 0)
{
try
{
Member m = new Member(MemberId);
return m.Text;
}
catch
{
return string.Empty;
}
}
else
return string.Empty;
}
/// <summary>
/// Get a media object as an xml object
/// </summary>
/// <param name="MediaId">The identifier of the media object to be returned</param>
/// <param name="Deep">If true, children of the media object is returned</param>
/// <returns>An umbraco xml node of the media (same format as a document node)</returns>
public static XPathNodeIterator GetMedia(int MediaId, bool Deep)
{
try
{
if (UmbracoConfig.For.UmbracoSettings().Content.UmbracoLibraryCacheDuration > 0)
{
XPathNodeIterator retVal = ApplicationContext.Current.ApplicationCache.GetCacheItem(
string.Format(
"{0}_{1}_{2}", CacheKeys.MediaCacheKey, MediaId, Deep),
TimeSpan.FromSeconds(UmbracoConfig.For.UmbracoSettings().Content.UmbracoLibraryCacheDuration),
() => GetMediaDo(MediaId, Deep));
if (retVal != null)
return retVal;
}
else
{
return GetMediaDo(MediaId, Deep);
}
}
catch
{
}
XmlDocument xd = new XmlDocument();
xd.LoadXml(string.Format("<error>No media is maching '{0}'</error>", MediaId));
return xd.CreateNavigator().Select("/");
}
private static XPathNodeIterator GetMediaDo(int mediaId, bool deep)
{
var m = new Media(mediaId);
if (m.nodeObjectType == Media._objectType)
{
var mXml = new XmlDocument();
var xml = m.ToXml(mXml, deep);
//This will be null if the media isn't public (meaning it is in the trash)
if (xml == null) return null;
//TODO: This is an aweful way of loading in XML - it is very slow.
mXml.LoadXml(xml.OuterXml);
var xp = mXml.CreateNavigator();
var xpath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "/node" : String.Format("/{0}", Casing.SafeAliasWithForcingCheck(m.ContentType.Alias));
return xp.Select(xpath);
}
return null;
}
/// <summary>
/// Get a member as an xml object
/// </summary>
/// <param name="MemberId">The identifier of the member object to be returned</param>
/// <returns>An umbraco xml node of the member (same format as a document node), but with two additional attributes on the "node" element:
/// "email" and "loginName".
/// </returns>
public static XPathNodeIterator GetMember(int MemberId)
{
try
{
if (UmbracoConfig.For.UmbracoSettings().Content.UmbracoLibraryCacheDuration > 0)
{
var retVal = ApplicationContext.Current.ApplicationCache.GetCacheItem(
string.Format(
"{0}_{1}", CacheKeys.MemberLibraryCacheKey, MemberId),
TimeSpan.FromSeconds(UmbracoConfig.For.UmbracoSettings().Content.UmbracoLibraryCacheDuration),
() => GetMemberDo(MemberId));
if (retVal != null)
return retVal.CreateNavigator().Select("/");
}
else
{
return GetMemberDo(MemberId).CreateNavigator().Select("/");
}
}
catch
{
}
XmlDocument xd = new XmlDocument();
xd.LoadXml(string.Format("<error>No member is maching '{0}'</error>", MemberId));
return xd.CreateNavigator().Select("/");
}
private static XmlDocument GetMemberDo(int MemberId)
{
Member m = new Member(MemberId);
XmlDocument mXml = new XmlDocument();
mXml.LoadXml(m.ToXml(mXml, false).OuterXml);
return mXml;
}
/// <summary>
/// Get the current member as an xml node
/// </summary>
/// <returns>Look in documentation for umbraco.library.GetMember(MemberId) for more information</returns>
public static XPathNodeIterator GetCurrentMember()
{
Member m = Member.GetCurrentMember();
if (m != null)
{
XmlDocument mXml = new XmlDocument();
mXml.LoadXml(m.ToXml(mXml, false).OuterXml);
XPathNavigator xp = mXml.CreateNavigator();
return xp.Select("/node");
}
XmlDocument xd = new XmlDocument();
xd.LoadXml(
"<error>No current member exists (best practice is to validate with 'isloggedon()' prior to this call)</error>");
return xd.CreateNavigator().Select("/");
}
/// <summary>
/// Whether or not the current user is logged in (as a member)
/// </summary>
/// <returns>True is the current user is logged in</returns>
public static bool IsLoggedOn()
{
return GetUmbracoHelper().MemberIsLoggedOn();
}
public static XPathNodeIterator AllowedGroups(int documentId, string path)
{
XmlDocument xd = new XmlDocument();
xd.LoadXml("<roles/>");
foreach (string role in Access.GetAccessingMembershipRoles(documentId, path))
xd.DocumentElement.AppendChild(xmlHelper.addTextNode(xd, "role", role));
return xd.CreateNavigator().Select(".");
}
/// <summary>
/// Check if a document object is protected by the "Protect Pages" functionality in umbraco
/// </summary>
/// <param name="DocumentId">The identifier of the document object to check</param>
/// <param name="Path">The full path of the document object to check</param>
/// <returns>True if the document object is protected</returns>
public static bool IsProtected(int DocumentId, string Path)
{
return GetUmbracoHelper().IsProtected(DocumentId, Path);
}
/// <summary>
/// Check if the current user has access to a document
/// </summary>
/// <param name="NodeId">The identifier of the document object to check</param>
/// <param name="Path">The full path of the document object to check</param>
/// <returns>True if the current user has access or if the current document isn't protected</returns>
public static bool HasAccess(int NodeId, string Path)
{
return GetUmbracoHelper().MemberHasAccess(NodeId, Path);
}
/// <summary>
/// Returns an MD5 hash of the string specified
/// </summary>
/// <param name="text">The text to create a hash from</param>
/// <returns>Md5 has of the string</returns>
public static string md5(string text)
{
return text.ToMd5();
}
/// <summary>
/// Compare two dates
/// </summary>
/// <param name="firstDate">The first date to compare</param>
/// <param name="secondDate">The second date to compare</param>
/// <returns>True if the first date is greater than the second date</returns>
public static bool DateGreaterThan(string firstDate, string secondDate)
{
if (DateTime.Parse(firstDate) > DateTime.Parse(secondDate))
return true;
else
return false;
}
/// <summary>
/// Compare two dates
/// </summary>
/// <param name="firstDate">The first date to compare</param>
/// <param name="secondDate">The second date to compare</param>
/// <returns>True if the first date is greater than or equal the second date</returns>
public static bool DateGreaterThanOrEqual(string firstDate, string secondDate)
{
if (DateTime.Parse(firstDate) >= DateTime.Parse(secondDate))
return true;
else
return false;
}
/// <summary>
/// Check if a date is greater than today
/// </summary>
/// <param name="firstDate">The date to check</param>
/// <returns>True if the date is greater that today (ie. at least the day of tomorrow)</returns>
public static bool DateGreaterThanToday(string firstDate)
{
DateTime first = DateTime.Parse(firstDate);
first = new DateTime(first.Year, first.Month, first.Day);
DateTime today = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
TimeSpan TS = new TimeSpan(first.Ticks - today.Ticks);
if (TS.Days > 0)
return true;
else
return false;
}
/// <summary>
/// Check if a date is greater than or equal today
/// </summary>
/// <param name="firstDate">The date to check</param>
/// <returns>True if the date is greater that or equal today (ie. at least today or the day of tomorrow)</returns>
public static bool DateGreaterThanOrEqualToday(string firstDate)
{
DateTime first = DateTime.Parse(firstDate);
first = new DateTime(first.Year, first.Month, first.Day);
DateTime today = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
TimeSpan TS = new TimeSpan(first.Ticks - today.Ticks);
if (TS.Days >= 0)
return true;
else
return false;
}
/// <summary>
/// Get the current date
/// </summary>
/// <returns>Current date i xml format (ToString("s"))</returns>
public static string CurrentDate()
{
return DateTime.Now.ToString("s");
}
/// <summary>
/// Add a value to a date
/// </summary>
/// <param name="Date">The Date to user</param>
/// <param name="AddType">The type to add: "y": year, "m": month, "d": day, "h": hour, "min": minutes, "s": seconds</param>
/// <param name="add">An integer value to add</param>
/// <returns>A date in xml format (ToString("s"))</returns>
public static string DateAdd(string Date, string AddType, int add)
{
return DateAddWithDateTimeObject(DateTime.Parse(Date), AddType, add);
}
/// <summary>
/// Get the day of week from a date matching the current culture settings
/// </summary>
/// <param name="Date">The date to use</param>
/// <returns>A string with the DayOfWeek matching the current contexts culture settings</returns>
public static string GetWeekDay(string Date)
{
return DateTime.Parse(Date).ToString("dddd");
}
/// <summary>
/// Add a value to a date. Similar to the other overload, but uses a datetime object instead of a string
/// </summary>
/// <param name="Date">The Date to user</param>
/// <param name="AddType">The type to add: "y": year, "m": month, "d": day, "h": hour, "min": minutes, "s": seconds</param>
/// <param name="add">An integer value to add</param>
/// <returns>A date in xml format (ToString("s"))</returns>
public static string DateAddWithDateTimeObject(DateTime Date, string AddType, int add)
{
switch (AddType.ToLower())
{
case "y":
Date = Date.AddYears(add);
break;
case "m":
Date = Date.AddMonths(add);
break;
case "d":
Date = Date.AddDays(add);
break;
case "h":
Date = Date.AddHours(add);
break;
case "min":
Date = Date.AddMinutes(add);
break;
case "s":
Date = Date.AddSeconds(add);
break;
}
return Date.ToString("s");
}
/// <summary>
/// Return the difference between 2 dates, in either minutes, seconds or years.
/// </summary>
/// <param name="firstDate">The first date.</param>
/// <param name="secondDate">The second date.</param>
/// <param name="diffType">format to return, can only be: s,m or y: s = seconds, m = minutes, y = years.</param>
/// <returns>A timespan as a integer</returns>
public static int DateDiff(string firstDate, string secondDate, string diffType)
{
TimeSpan TS = DateTime.Parse(firstDate).Subtract(DateTime.Parse(secondDate));
switch (diffType.ToLower())
{
case "m":
return Convert.ToInt32(TS.TotalMinutes);
case "s":
return Convert.ToInt32(TS.TotalSeconds);
case "y":
return Convert.ToInt32(TS.TotalDays / 365);
}
// return default
return 0;
}
/// <summary>
/// Formats a string to the specified formate.
/// </summary>
/// <param name="Date">The date.</param>
/// <param name="Format">The format, compatible with regular .net date formats</param>
/// <returns>A date in the new format as a string</returns>
public static string FormatDateTime(string Date, string Format)
{
DateTime result;
if (DateTime.TryParse(Date, out result))
return result.ToString(Format);
return string.Empty;
}
/// <summary>
/// Converts a string to Long Date and returns it as a string
/// </summary>
/// <param name="Date">The date.</param>
/// <param name="WithTime">if set to <c>true</c> the date will include time.</param>
/// <param name="TimeSplitter">The splitter between date and time.</param>
/// <returns>A Long Date as a string.</returns>
public static string LongDate(string Date, bool WithTime, string TimeSplitter)
{
DateTime result;
if (DateTime.TryParse(Date, out result))
{
if (WithTime)
return result.ToLongDateString() + TimeSplitter + result.ToLongTimeString();
return result.ToLongDateString();
}
return string.Empty;
}
/// <summary>
/// Checks whether the Culture with the specified name exixts in the standard .net cultureInfo.
/// </summary>
/// <param name="cultureName">Name of the culture.</param>
/// <returns></returns>
public static bool CultureExists(string cultureName)
{
CultureInfo[] ci = CultureInfo.GetCultures(CultureTypes.AllCultures);
CultureInfo c = Array.Find(ci, delegate(CultureInfo culture) { return culture.Name == cultureName; });
return c != null;
}
/// <summary>
/// Converts a string to datetime in the longdate with day name format.
/// </summary>
/// <param name="Date">The date.</param>
/// <param name="DaySplitter">String between day name and date</param>
/// <param name="WithTime">if set to <c>true</c> the datetiem will include time.</param>
/// <param name="TimeSplitter">String between date and time.</param>
/// <param name="GlobalAlias">Culture name.</param>
/// <returns>A datetime in the longdate formate with day name, as a string</returns>
public static string LongDateWithDayName(string Date, string DaySplitter, bool WithTime, string TimeSplitter,
string GlobalAlias)
{
if (!CultureExists(GlobalAlias))
return string.Empty;
DateTime result;
CultureInfo.GetCultureInfo(GlobalAlias);
DateTimeFormatInfo dtInfo = CultureInfo.GetCultureInfo(GlobalAlias).DateTimeFormat;
if (DateTime.TryParse(Date, dtInfo, DateTimeStyles.None, out result))
{
if (WithTime)
return
result.ToString(dtInfo.LongDatePattern) + TimeSplitter + result.ToString(dtInfo.LongTimePattern);
return result.ToString(dtInfo.LongDatePattern);
}
return string.Empty;
}
/// <summary>
/// Converts a string to a Long Date and returns it as a string
/// </summary>
/// <param name="Date">The date.</param>
/// <returns>A Long Date as a string.</returns>
public static string LongDate(string Date)
{
DateTime result;
if (DateTime.TryParse(Date, out result))
return result.ToLongDateString();
return string.Empty;
}
/// <summary>
/// Converts a string to a Short Date and returns it as a string
/// </summary>
/// <param name="Date">The date.</param>
/// <returns>A Short Date as a string.</returns>
public static string ShortDate(string Date)
{
DateTime result;
if (DateTime.TryParse(Date, out result))
return result.ToShortDateString();
return string.Empty;
}
/// <summary>
/// Converts a string to a Short Date, with a specific culture, and returns it as a string
/// </summary>
/// <param name="Date">The date.</param>
/// <param name="GlobalAlias">Culture name</param>
/// <returns>A short date with a specific culture, as a string</returns>
public static string ShortDateWithGlobal(string Date, string GlobalAlias)
{
if (!CultureExists(GlobalAlias))
return string.Empty;
DateTime result;
if (DateTime.TryParse(Date, out result))
{
DateTimeFormatInfo dtInfo = CultureInfo.GetCultureInfo(GlobalAlias).DateTimeFormat;
return result.ToString(dtInfo.ShortDatePattern);
}
return string.Empty;
}
/// <summary>
/// Converts a string to a Short Date with time, with a specific culture, and returns it as a string
/// </summary>
/// <param name="Date">The date.</param>
/// <param name="GlobalAlias">Culture name</param>
/// <returns>A short date withi time, with a specific culture, as a string</returns>
public static string ShortDateWithTimeAndGlobal(string Date, string GlobalAlias)
{
if (!CultureExists(GlobalAlias))
return string.Empty;
DateTime result;
if (DateTime.TryParse(Date, out result))
{
DateTimeFormatInfo dtInfo = CultureInfo.GetCultureInfo(GlobalAlias).DateTimeFormat;
return result.ToString(dtInfo.ShortDatePattern) + " " +
result.ToString(dtInfo.ShortTimePattern);
}
return string.Empty;
}
/// <summary>
/// Converts a datetime string to the ShortTime format.
/// </summary>
/// <param name="Date">The date.</param>
/// <returns></returns>
public static string ShortTime(string Date)
{
DateTime result;
if (DateTime.TryParse(Date, out result))
return result.ToShortTimeString();
return string.Empty;
}
/// <summary>
/// Converts a datetime string to the ShortDate format.
/// </summary>
/// <param name="Date">The date.</param>
/// <param name="WithTime">if set to <c>true</c> the date will include time.</param>
/// <param name="TimeSplitter">String dividing date and time</param>
/// <returns></returns>
public static string ShortDate(string Date, bool WithTime, string TimeSplitter)
{
DateTime result;
if (DateTime.TryParse(Date, out result))
{
if (WithTime)
return result.ToShortDateString() + TimeSplitter + result.ToLongTimeString();
return result.ToShortDateString();
}
return string.Empty;
}
/// <summary>
/// Replaces text line breaks with html line breaks
/// </summary>
/// <param name="text">The text.</param>
/// <returns>The text with text line breaks replaced with html linebreaks (<br/>)</returns>
public static string ReplaceLineBreaks(string text)
{
return GetUmbracoHelper().ReplaceLineBreaksForHtml(text);
}
/// <summary>
/// Renders the content of a macro. Uses the normal template umbraco macro markup as input.
/// This only works properly with xslt macros.
/// Python and .ascx based macros will not render properly, as viewstate is not included.
/// </summary>
/// <param name="Text">The macro markup to be rendered.</param>
/// <param name="PageId">The page id.</param>
/// <returns>The rendered macro as a string</returns>
public static string RenderMacroContent(string Text, int PageId)
{
try
{
page p = new page(((IHasXmlNode)GetXmlNodeById(PageId.ToString()).Current).GetNode());
template t = new template(p.Template);
Control c = t.parseStringBuilder(new StringBuilder(Text), p);
StringWriter sw = new StringWriter();