This repository was archived by the owner on Feb 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVariousExtensions.cs
291 lines (246 loc) · 10.3 KB
/
VariousExtensions.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
/* Copyright (C) 2014 NAVERTICA a.s. http://www.navertica.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.SharePoint;
namespace Navertica.SharePoint.Extensions
{
/// <summary>
/// Navertica SharePoint Tools
/// </summary>
public static class ExtensionsTools
{
public static void AddViewFields(this SPView view, IEnumerable<string> fields, bool deleteCurrentViewFields = false)
{
if (view == null) throw new ArgumentNullException("view");
if (deleteCurrentViewFields)
{
view.ViewFields.DeleteAll();
}
foreach (string fldIntName in fields)
{
if (!view.ViewFields.Exists(fldIntName))
{
view.ViewFields.Add(fldIntName);
}
}
view.Update();
}
public static string GetProperties(this object obj)
{
if (obj == null) throw new ArgumentNullException("obj");
return obj.GetType().GetProperties().OrderBy(i => i.Name).Select(i => i.Name + " [" + i.PropertyType.Name + "]").JoinStrings();
}
public static DictionaryNVR GetValueForAllCultures(this SPUserResource resource)
{
SPWeb web = resource.Parent.GetType() == typeof (SPWeb) ? (SPWeb) resource.Parent : ( (SPList) resource.Parent ).ParentWeb;
DictionaryNVR values = new DictionaryNVR();
foreach (CultureInfo info in web.RegionalSettings.InstalledLanguages.Cast<SPLanguage>().Select(l => CultureInfo.GetCultureInfo(l.LCID)))
{
values[info.LCID.ToString(CultureInfo.InvariantCulture)] = resource.GetValueForUICulture(info);
}
return values;
}
public static bool IsEmpty(this Guid guid)
{
return guid == Guid.Empty;
}
/// <summary>
/// Returns true if datetime is in interval
/// </summary>
/// <param name="dateTime"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public static bool IsInInterval(this DateTime dateTime, DateTime start, DateTime end)
{
if (dateTime == null) throw new ArgumentNullException("dateTime");
return start.CompareTo(dateTime) < 0 && end.CompareTo(dateTime) > 0;
}
/// <summary>
/// Reads data from a stream until the end is reached. The
/// data is returned as a byte array. An IOException is
/// thrown if any of the underlying IO calls fail.
/// </summary>
/// <param name="stream">The stream to read data from</param>
public static byte[] ReadFully(this Stream stream)
{
if (stream == null) throw new ArgumentNullException();
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
/// <summary>
/// Replaces invalid characters in a file name
/// </summary>
/// <param name="fname"></param>
/// <param name="replaceWith"></param>
/// <returns></returns>
public static string ReplaceInvalidFileNameChars(this string fname, char replaceWith)
{
// pokud mame v datech _UID, je to string obsahujici strednikem oddelena jmena parametru, ktera tvori primarni klic
// a ktera tedy predradime pred jmeno souboru, aby se soubory se stejnym jmenem pro ruzne polozky neprepisovaly
List<char> invalidChars = new List<char>(Path.GetInvalidFileNameChars()) { '#', '%', '&', '*', ':', '<', '>', '?', '/', '{', '|', '}' };
return invalidChars.Aggregate(fname, (current, c) => current.Replace(c, replaceWith)).Replace("..", replaceWith.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Reads data from a stream until the end is reached. The
/// data is returned as a byte array. An IOException is
/// thrown if any of the underlying IO calls fail.
/// http://www.yoda.arachsys.com/csharp/readbinary.html
/// </summary>
/// <param name="stream">The stream to read data from</param>
///
public static byte[] StreamToByteArray(this Stream stream)
{
if (stream == null) throw new ArgumentNullException();
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0) return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
#region Conversion functions
/// <summary>
/// Returns false if object is null else true. If not null tries parse value to boolean
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static bool ToBool(this object val)
{
if (val is bool) return (bool) val;
string value = ( val ?? "" ).ToString().Trim();
bool result = false;
if (string.IsNullOrEmpty(value)) return false;
try
{
result = Convert.ToBoolean(val);
}
catch
{
try
{
int boolVal = int.Parse(value);
result = Convert.ToBoolean(boolVal);
}
catch
{
if (value.ToLowerInvariant().EqualAny(new[] { "on", "yes", "ano" })) result = true;
}
}
return result;
}
public static int ToInt(this object value)
{
if (value is int) return (int) value;
try
{
return Convert.ToInt32(value);
}
catch
{
return Int32.MinValue;
}
}
public static double ToDouble(this object value)
{
try
{
return Convert.ToDouble(value);
}
catch
{
return Double.NaN;
}
}
#endregion
public static string ToStringISO(this DateTime dateTime, CultureInfo culture = null)
{
if (dateTime == null) throw new ArgumentNullException("dateTime");
if (culture == null) culture = CultureInfo.InvariantCulture;
return dateTime.ToString("s", culture);
}
public static string ToStringLocalized(this DateTime dateTime, bool incudeTime = false, int lang = -1)
{
if (dateTime == null) throw new ArgumentNullException("dateTime");
CultureInfo culture = CultureInfo.CurrentUICulture;
DateTimeFormatInfo format = culture.DateTimeFormat;
if (lang > 0)
{
culture = CultureInfo.GetCultureInfo(lang);
format = culture.DateTimeFormat;
}
string result = dateTime.ToString(format.ShortDatePattern, culture);
if (incudeTime) result += " " + dateTime.ToString(format.ShortTimePattern);
return result;
}
/// <summary>
/// Extends System.Type to get all extension methods. It searches all assemblies which are known by the current AppDomain.
/// </summary>
/// <remarks>
/// Insired by Jon Skeet from his answer on http://stackoverflow.com/questions/299515/c-sharp-reflection-to-identify-extension-methods
/// </remarks>
/// <returns>returns MethodInfo[] with found extension methods</returns>
public static MethodInfo[] GetExtensionMethods(this Type t)
{
List<Type> assemblyTypes = new List<Type>();
var asss = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly item in asss)
{
try
{
assemblyTypes.AddRange(item.GetTypes());
}
catch (Exception) {}
}
var query = from type in assemblyTypes
where type.IsSealed && !type.IsGenericType && !type.IsNested
from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
where method.IsDefined(typeof (ExtensionAttribute), false)
where method.GetParameters()[0].ParameterType == t
select method;
return query.ToArray();
}
/// <summary>
/// Extends System.Type to search for a given extension method name
/// </summary>
/// <param name="t"></param>
/// <param name="extMethodName">Name of the extension method</param>
/// <returns>the found method or null</returns>
public static MethodInfo GetExtensionMethod(this Type t, string extMethodName)
{
var mi = from extMethod in t.GetExtensionMethods() where extMethod.Name == extMethodName select extMethod;
if (!mi.Any())
return null;
return mi.First();
}
}
}