1 using System;
2 using System.Collections;
3 using System.Text;
4 using System.IO;
5 using System.Reflection;
6 using System.Globalization;
7 using System.Runtime.InteropServices;
8 using org.xmlBlaster.client; // for XmlBlasterException TODO: move to util
9
10 namespace org.xmlBlaster.util {
11 ///
12 /// @author mr@marcelruff.info 2007 http://www.xmlBlaster.org
13 ///
14 public class Stuff {
15 /// <summary>
16 /// Converts a DateTime to an ISO 8601 datetime string with timezone indicator
17 /// See http://en.wikipedia.org/wiki/ISO_8601#Time_zones for info
18 /// The result is of type "yyyy'-'MM'-'dd HH':'mm':'ss'.'FFF'Z'"
19 /// </summary>
20 /// <param name="DateTimeToConvert">The DateTime to be converted</param>
21 /// <returns>e.g. "2007-07-09 07:10:18.906Z"</returns>
22 public static string ToUtcIsoDateTimeString(DateTime dateTimeToConvert) {
23 DateTime utc = dateTimeToConvert.ToUniversalTime();
24 // "s" creates "2007-01-01T14:26:20": Note the missing 'Z' which means it is local time
25 // "u" creates "2007-01-01 14:26:20Z": Note the valid ' ' instead of 'T' and correct UTC ending
26 //string isoUtc = utc.ToString("u");
27 //see ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.en/cpref8/html/T_System_Globalization_DateTimeFormatInfo.htm
28 string isoUtc = utc.ToString("yyyy'-'MM'-'dd HH':'mm':'ss'.'FFF'Z'");
29 //if (!isoUtc.EndsWith("Z"))
30 // isoUtc += "Z";
31 //isoUtc.Replace(' ', 'T');
32 return isoUtc;
33 }
34
35 /// <summary>
36 /// The UNIX epoch, midnight, January 1, 1970 UTC
37 /// </summary>
38 public static readonly DateTime StartOfEpochUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
39 //public static readonly DateTime StartOfEpochUtc = new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
40
41 /// <summary>
42 /// Get the elapsed UTC! milliseconds since 1970 for the given time,
43 /// is compatible to Javas System.currentTimeMillis()
44 /// See the bug http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1421898&SiteID=1
45 /// .net returns different values for different local times!
46 /// This method corrects it to UTC.
47 /// </summary>
48 /// <param name="dateTime">E.g. DateTime.UtcNow</param>
49 /// <returns>
50 /// The difference, measured in milliseconds, between
51 /// the given time and midnight, January 1, 1970 UTC.
52 /// </returns>
53 public static long ToUtcMillisecondsEpoch(DateTime dateTime) {
54 // TimeSpan.TicksPerMillisecond == 10000
55 return ((dateTime.ToUniversalTime() - StartOfEpochUtc).Ticks / TimeSpan.TicksPerMillisecond);
56 //return ((dateTime - StartOfEpoch).Ticks / 10000);
57 //TimeSpan span = DateTime.UtcNow-StartOfEpoch;
58 //return TimeSpan.TicksPerMillisecond;
59 }
60
61 /// <summary>
62 /// UTC millis (similar to java)
63 /// </summary>
64 /// <returns>
65 /// The difference, measured in milliseconds, between
66 /// the current UTC time and midnight, January 1, 1970 UTC.
67 /// </returns>
68 public static long GetCurrentUtcMillisecondsEpoch() {
69 return ((DateTime.UtcNow - StartOfEpochUtc).Ticks / TimeSpan.TicksPerMillisecond);
70 }
71
72 /// <summary>
73 /// Get the DateTime from a java System.currentTimeMillis()
74 /// </summary>
75 /// <param name="milliEpoch">
76 /// The difference, measured in milliseconds, between
77 /// the given time and midnight, January 1, 1970 UTC.
78 /// </param>
79 /// <returns>
80 /// UTC
81 /// </returns>
82 public static DateTime DateTimeFromUtcMillisecondsEpoch(long milliEpoch) {
83 return new DateTime(StartOfEpochUtc.Ticks + (milliEpoch * 10000), DateTimeKind.Utc);
84 }
85
86 public static bool Get(Hashtable properties, string key, bool defaultValue)
87 {
88 if (properties == null || key == null) return defaultValue;
89 if (!properties.ContainsKey(key)) return defaultValue;
90 string value = (string)properties[key];
91 return Boolean.Parse(value);
92 }
93
94 public static long Get(Hashtable properties, string key, long defaultValue)
95 {
96 if (properties == null || key == null) return defaultValue;
97 if (!properties.ContainsKey(key)) return defaultValue;
98 string value = (string)properties[key];
99 return Int64.Parse(value);
100 }
101
102 public static string Get(Hashtable properties, string key, string defaultValue)
103 {
104 if (properties == null || key == null) return defaultValue;
105 if (!properties.ContainsKey(key)) return defaultValue;
106 return (string)properties[key];
107 }
108
109 /*
110 /// <summary>
111 ///
112 /// </summary>
113 /// <param name="nanos">Elapsed since 1970</param>
114 /// <returns></returns>
115 public DateTime NanosToDateTime(string nanos) {
116 long nanos = 0;
117 try {
118 nanos = long.Parse(nanos);
119 }
120 catch (Exception) {
121 return null;
122 }
123 long millis = nanos / 1000 / 1000;
124 DateTime. How??
125 }
126 */
127 /// <summary>
128 /// </summary>
129 /// <param name="dateTimeIso8601">2007-01-01T14:26:20Z</param>
130 /// <returns>If dateTimeIso8601 == null we return the current time</returns>
131 public static DateTime UtcDateTimeFromIsoString(string dateTimeIso8601) {
132 if (dateTimeIso8601 == null || dateTimeIso8601.Trim() == "")
133 return DateTime.UtcNow;
134 //DateTime newDate = DateTime.TryParse(dateTimeIso8601, "u", null);
135 return DateTime.Parse(dateTimeIso8601, CultureInfo.InvariantCulture);
136 }
137
138 public readonly static string AMP = "&";
139 public readonly static string LT = "<";
140 public readonly static string GT = ">";
141 public readonly static string QUOT = """;
142 public readonly static string APOS = "'";
143
144 public readonly static string SLASH_R = "
";
145 public readonly static string NULL = "�";
146
147 /**
148 * Escape predefined xml entities (&, <, >, ', ").
149 * Additionally the '\0' is escaped.
150 * @param text
151 * @return The escaped text is appended to the given StringBuffer.
152 * @deprecated Use XmlBuffer.cs!!!!
153 */
154 public static string EscapeXml(String text) {
155 string ret = "";
156 if (text == null) return ret;
157 int length = text.Length;
158 for (int i = 0; i < length; i++) {
159 char c = text[i];
160 switch (c) {
161 case '\0':
162 ret += NULL;
163 break;
164 case '&':
165 ret += AMP;
166 break;
167 case '<':
168 ret += LT;
169 break;
170 case '>':
171 ret += GT;
172 break;
173 case '"':
174 ret += QUOT;
175 break;
176 case '\'':
177 ret += APOS;
178 break;
179 case '\r':
180 ret += SLASH_R;
181 break;
182 default:
183 ret += c;
184 break;
185 }
186 }
187 return ret;
188 }
189
190 /// <summary>
191 /// Creates an XML string with <clientProperty name='key'>value</clientProperty>
192 /// format which can be used e.g. for the ConnectQos.
193 /// </summary>
194 /// <param name="h"></param>
195 /// <param name="addNewline"></param>
196 /// <returns></returns>
197 public static string ToClientPropertiesXml(Hashtable h, bool addNewline) {
198 string nl = (addNewline) ? "\n" : "";
199 string xml = "";
200 foreach (string key in h.Keys) {
201 string value = (string)h[key];
202 xml += nl;
203 xml += " <clientProperty name='";
204 xml += EscapeXml(key);
205 xml += ("'>");
206 xml += EscapeXml(value);
207 xml += ("</clientProperty>");
208 }
209 return xml;
210 }
211
212 /**
213 * If this clientProperty is send with ConnectQos the clientProperties are
214 * copied to the SessionInfo.remoteProperty map (which are manipulatable by jconsole and EventPlugin)
215 */
216 public static readonly String CLIENTPROPERTY_REMOTEPROPERTIES = "__remoteProperties";
217
218 /// <summary>
219 /// Adds some environment information to the Hashtable
220 /// </summary>
221 /// <param name="info">"version.OS", "version.net" and more</param>
222 public static void GetInfoProperties(Hashtable info) {
223 if (info == null) return;
224 info[CLIENTPROPERTY_REMOTEPROPERTIES] = "true";
225
226 // "Microsoft Windows CE 5.2.1238", "Microsoft Windows CE 5.1.195", "Microsoft Windows CE 4.21.1088"
227 info["version.OS"] = System.Environment.OSVersion.ToString();
228
229 // "2.0.7045.0", "2.0.6129.0", "2.0.7045.0"
230 info["version.net"] = System.Environment.Version.ToString();
231
232 //"", "de-DE", "en-US"
233 info["location"] = CultureInfo.CurrentCulture.ToString();
234
235 // screenSize "240x320", "240x240"
236 try {
237 //info["version.xmlBlasterC#"] = xb.GetVersion();
238
239 // "HERM200", "hp IPAQ hw6910", "Microsoft DeviceEmulator"
240 info["info.OEM"] = GetOemInfo();
241
242 //info["logical.drive"] = Info.GetLogicalDrives();
243 //info["machine.name"] = Info.MachineName;
244
245 // "PocketPC", "PocketPC", "PocketPC"
246 info["platform.name"] = GetPlatformName();
247 }
248 catch (Exception) {
249 }
250 }
251
252 #if (WINCE || Smartphone || PocketPC || WindowsCE || CF1)
253
254
255 //#if XMLBLASTER_WINCE (was not activated, why? see PInvoke.cs)
256 struct SYSTEMTIME {
257 public void LoadDateTime(DateTime dateTime) {
258 this.Year = (UInt16)dateTime.Year;
259 this.Month = (UInt16)dateTime.Month;
260 this.Day = (UInt16)dateTime.Day;
261 this.Hour = (UInt16)dateTime.Hour;
262 this.Minute = (UInt16)dateTime.Minute;
263 this.Second = (UInt16)dateTime.Second;
264 this.MilliSecond = (UInt16)dateTime.Millisecond;
265 }
266 public UInt16 Year;
267 public UInt16 Month;
268 public UInt16 DayOfWeek;
269 public UInt16 Day;
270 public UInt16 Hour;
271 public UInt16 Minute;
272 public UInt16 Second;
273 public UInt16 MilliSecond;
274 }
275
276 [DllImport("Coredll.dll", EntryPoint = "SetSystemTime")]
277 private static extern bool SetSystemTime(ref SYSTEMTIME st);
278
279 public static bool UpdateSystemTime(DateTime serverTime) {
280 serverTime = serverTime.ToUniversalTime();
281 SYSTEMTIME sysTime = new SYSTEMTIME();
282 sysTime.LoadDateTime(serverTime);
283 bool worked = SetSystemTime(ref sysTime);
284 return worked;
285 }
286
287 [DllImport("coredll.dll", EntryPoint = "SystemParametersInfo", SetLastError = true)]
288 internal static extern bool SystemParametersInfo(int action, int size, byte[] buffer, int winini);
289
290 /// <summary>
291 /// Returns a string which identifies the device platform, e.g. "PocketPC" or "SmartPhone" or "CEPC platform" (emulator)
292 /// </summary>
293 public static string GetPlatformName() {
294 byte[] buffer = new byte[48];
295 int SystemParametersInfoAction_GetPlatformType = 257;
296 int SystemParametersInfoFlags_None = 0;
297 if (!SystemParametersInfo(SystemParametersInfoAction_GetPlatformType, buffer.Length, buffer, SystemParametersInfoFlags_None)) {
298 int err = Marshal.GetLastWin32Error();
299 throw new XmlBlasterException(XmlBlasterException.INTERNAL_UNKNOWN, "Retrieving platform name failed: " + err);
300 }
301 string platformname = System.Text.Encoding.Unicode.GetString(buffer, 0, buffer.Length);
302 return platformname.Substring(0, platformname.IndexOf("\0")); // trim trailing null
303 }
304
305 /// <summary>
306 /// Returns OEM specific information from the device, e.g. "hp iPAQ hw6910"
307 /// </summary>
308 public static string GetOemInfo() {
309 byte[] buffer = new byte[128];
310 int SystemParametersInfoAction_GetOemInfo = 258;
311 int SystemParametersInfoFlags_None = 0;
312 if (!SystemParametersInfo(SystemParametersInfoAction_GetOemInfo, buffer.Length, buffer, SystemParametersInfoFlags_None)) {
313 int err = Marshal.GetLastWin32Error();
314 throw new XmlBlasterException(XmlBlasterException.INTERNAL_UNKNOWN, "Retrieving OEM info failed: " + err);
315 }
316 string oeminfo = System.Text.Encoding.Unicode.GetString(buffer, 0, buffer.Length);
317 return oeminfo.Substring(0, oeminfo.IndexOf("\0"));
318 }
319
320 /*
321 /// Returns an array of string containing the names of the logical drives on the current computer.
322 /// <returns>An array of string where each element contains the name of a logical drive.</returns>
323 public static string[] GetLogicalDrives() {
324 // storage cards are directories with the temporary attribute
325 System.IO.FileAttributes attrStorageCard = System.IO.FileAttributes.Directory | System.IO.FileAttributes.Temporary;
326 ArrayList drives = new ArrayList();
327 drives.Add("\\");
328 DirectoryInfo rootDir = new DirectoryInfo(@"\");
329 foreach (DirectoryInfo di in rootDir.GetDirectories()) {
330 // only directory and temporary
331 if ((di.Attributes & attrStorageCard) == attrStorageCard) {
332 drives.Add(di.Name);
333 }
334 }
335 return (string[])drives.ToArray(typeof(string));
336
337 }
338 */
339 /*
340 public static string GetMachineName() {
341 string machineName = "";
342 try {
343 RegistryKey ident = Registry.LocalMachine.OpenSubKey("Ident");
344 machineName = ident.GetValue("Name").ToString();
345 ident.Close();
346 }
347 catch {
348 throw new PlatformNotSupportedException();
349 }
350 return machineName;
351 }
352 */
353 #else // !XMLBLASTER_WINCE
354 public static string GetPlatformName() {
355 return ""; // TODO
356 }
357 public static string GetOemInfo() {
358 return ""; // TODO
359 }
360 #endif
361 }
362 }
syntax highlighted by Code2HTML, v. 0.9.1