ViewVC Help
View File | Revision Log | Show Annotations | Download File | View Changeset | Root Listing
root/AnywhereTS-MSSQL/trunk/TSAdminTool/ProSupport.cs
Revision: 123
Committed: Sat Jul 14 11:14:09 2012 UTC (10 years, 10 months ago) by william
File size: 31794 byte(s)
Log Message:
+ bulk commit
-- add SQLSerer SMO support for executing TSQL commands

File Contents

# Content
1
2 using System;
3 using System.Collections;
4 using System.Collections.Generic;
5 using System.Text;
6 using System.Windows.Forms;
7 using System.Globalization;
8 using System.Data;
9 using System.Security.AccessControl;
10 using System.Security.Principal;
11 using System.IO;
12 using System.Management;
13 using System.Net;
14 using log4net;
15
16 // Support class for the AnywhereTS version. This file should only be included in the Pro version.
17 namespace AnywhereTS
18 {
19 public static class ProSupport
20 {
21 // File names
22 public const string strHostsFilename = "hosts"; // The name of the thin clients host file.
23 public const string strNetworkConfigFilename = "network"; // Name of the Thinstation common config file in the TFTP root directory.
24 public const string strDatabaseFilename = "ats.mdf"; // Name of the AnywhereTS SQL express database file.
25 public const string strDatabaseFilename2 = "ats_log.ldf"; // Name of the AnywhereTS SQL express database log file.
26
27 // Registry keys
28 public const string strRegTFTP_root = "TFTP_root"; // Reg key for TFTP root directory in database
29 public const string strRegDatabaseDir = "DatabaseDir"; // Reg key for database directory
30 public const string strRegAnywhereTSServer = "ATSServer"; // Reg key for database server
31 public const string strRegDatabaseServer = "DatabaseServer"; // Reg key for database server
32 public const string strRegDatabaseInstance = "DatabaseInstance"; // Reg key for database server
33 public const string strRegDestDir = "DestDir"; // Reg key for Destination directory, used in unmanged mode..
34
35 // Database constants
36 public const string DEFAULT_RECORD_MAC = "Default "; // Phony MAC address (12 chars) used to identify the client record that contains the default settings for all new clients
37
38 // Database variables
39 public static atsDataSetTableAdapters.ClientTableAdapter clientTableAdapter; // The AnywhereTS application data adapter for the clients table. Only this adapter should be used.
40 public static atsDataSetTableAdapters.TftpServerTableAdapter tftpServerTableAdapter; // The AnywhereTS application data adapter for the TFTP servers table. Only this adapter should be used.
41 public static atsDataSetTableAdapters.TerminalServerTableAdapter terminalServerTableAdapter; // The AnywhereTS application data adapter for the terminal servers table. Only this adapter should be used.
42 public static atsDataSetTableAdapters.AppInfoTableAdapter appInfoTableAdapter; // The AnywhereTS application data adapter for the AppInfo table. Only this adapter should be used.
43
44 public static string strAnywhereTSServer; // If this computer does not contain the database server, this is the name of the database server that contains the ATS database. Used by the Control Panel
45 public static string strDatabaseServer; // If this computer does not contain the database server, this is the name of the database server that contains the ATS database. Used by the Control Panel
46 public static string strDatabaseInstance; // If this computer does not contain the database server, this is the name of the database server that contains the ATS database. Used by the Control Panel
47
48 // Directories
49 //public static string strDatabasePath; // The directory where the database file is located.
50 public static string strDestDir; // Destination directory for client files in unmanaged mode.
51
52 // Constructor Initializes the global variables
53 static ProSupport()
54 {
55 // Initiate variables from registry
56 strAnywhereTSServer = ATSGlobals.GetATSRegValueString(strRegAnywhereTSServer);
57 //strDatabasePath = ATSGlobals.GetATSRegValueString(strRegDatabaseDir);
58 strDestDir = ATSGlobals.GetATSRegValueString(strRegDestDir);
59 strDatabaseServer = ATSGlobals.GetATSRegValueString(strRegDatabaseServer);
60 strDatabaseInstance = ATSGlobals.GetATSRegValueString(strRegDatabaseInstance);
61 }
62
63 // Loook up local IP for computer
64 public static void ThisComputerIp (System.Windows.Forms.ComboBox combo, bool bolServerName)
65 {
66 ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
67
68 ManagementObjectCollection queryCollection = query.Get();
69 combo.Items.Clear();
70 if (bolServerName == true) //Add computer name
71 {
72 combo.Items.Add(Dns.GetHostName());
73 }
74 foreach (ManagementObject mo in queryCollection)
75 {
76 string[] addresses = (string[])mo["IPAddress"];
77 foreach (string ipaddress in addresses)
78 {
79 if (ipaddress !="0.0.0.0")
80 combo.Items.Add(ipaddress);
81
82 }
83 }
84 }
85
86 // Compate two DriveInfo arrays and return TRUE if they are equal.
87 public static bool CompareDriveInfoArrays(List<DriveInfo> data1, List<DriveInfo> data2)
88 {
89 // If both are null, they're equal
90 if (data1 == null && data2 == null)
91 {
92 return true;
93 }
94 // If either but not both are null, they're not equal
95 if (data1 == null || data2 == null)
96 {
97 return false;
98 }
99 if (data1.Count != data2.Count)
100 {
101 return false;
102 }
103 for (int i = 0; i < data1.Count; i++)
104 {
105 if (data1[i].Name + data1[i].VolumeLabel != data2[i].Name + data2[i].VolumeLabel)
106 {
107 return false;
108 }
109 }
110 return true;
111 }
112
113 // Get an IP parameter (IP, netmask, gateway) from the local machine
114 // Paramters:
115 // Out: IP address in the format "x.x.x.x"
116 // strNetworkConf = "IPAddress": Get IPAddress
117 // strNetworkConf = "IPSubnet": Get netmask
118 // strNetworkConf = "DefaultIPGateway": Get gateway
119 // strNetworkConf = "Description": Get network card
120 // strNetworkConf = "MACAddress": Get MAC address
121 // strNetworkConf = "DNSServerSearchOrder": Get DNS
122 public static string ThisComputerNetworkConf(string strNetworkConf)
123 {
124 ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
125 ManagementObjectCollection queryCollection = query.Get();
126 foreach (ManagementObject mo in queryCollection)
127 {
128 string[] addresses = (string[])mo[strNetworkConf];
129 return addresses[0];
130 }
131 return ""; // No network adapter found.
132 }
133
134 // Initiate the database
135 public static void InitDatabase()
136 {
137 //// Create and set the connection string
138 //string dataServerName; // The name of the database server in the connection string
139 //if (strDatabaseServer.Length != 0)
140 //{ // We have a database server
141 // dataServerName = strDatabaseServer;
142 //}
143 //else
144 //{ // We do not have an external, data server.
145 // dataServerName = ".";
146 //}
147 //Properties.Settings.Default["atsConnectionString"] = @"Data Source=" + dataServerName + @"\SQLEXPRESS;Database='AnywhereTS';Integrated Security=True;Connect Timeout=30;User Instance=False";
148 //Properties.Settings.Default.Save();
149
150 // Set up table adapters
151 clientTableAdapter = new atsDataSetTableAdapters.ClientTableAdapter();
152 tftpServerTableAdapter = new atsDataSetTableAdapters.TftpServerTableAdapter();
153 terminalServerTableAdapter = new atsDataSetTableAdapters.TerminalServerTableAdapter();
154 appInfoTableAdapter = new atsDataSetTableAdapters.AppInfoTableAdapter();
155 }
156
157 // Adds an ACL entry for RW access on the specified file for Remote desktop users.
158 [Obsolete("GrantRWaccessForRemoteDesktopUsers has been deprecated - define user access rights via SQL Server")]
159 public static void GrantRWaccessForRemoteDesktopUsers(string fileName)
160 {
161 // Get a FileSecurity object that represents the current security settings.
162 FileSecurity fSecurity = File.GetAccessControl(fileName);
163
164 // Add FileSystemAccessRule:s to the security settings.
165 // Remote desktop users can read and write, but not delete
166 fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinRemoteDesktopUsersSid, null), FileSystemRights.Read, AccessControlType.Allow));
167 fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinRemoteDesktopUsersSid, null), FileSystemRights.Write, AccessControlType.Allow));
168
169 // Set the new access settings.
170 File.SetAccessControl(fileName, fSecurity);
171 }
172
173 // Adds an ACL entry for ReadWriteModify access on the specified file for Remote desktop users.
174 [Obsolete("GrantRWMaccessForRemoteDesktopUsers has been deprecated - define user access rights via SQL Server")]
175 public static void GrantRWMaccessForRemoteDesktopUsers(string fileName)
176 {
177 // Get a FileSecurity object that represents the current security settings.
178 FileSecurity fSecurity = File.GetAccessControl(fileName);
179
180 // Add FileSystemAccessRule:s to the security settings.
181 // Remote desktop users can read and write, but not delete
182 fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinRemoteDesktopUsersSid, null), FileSystemRights.Read, AccessControlType.Allow));
183 fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinRemoteDesktopUsersSid, null), FileSystemRights.Write, AccessControlType.Allow));
184 fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinRemoteDesktopUsersSid, null), FileSystemRights.Modify, AccessControlType.Allow));
185
186 // Set the new access settings.
187 File.SetAccessControl(fileName, fSecurity);
188 }
189
190 // (obsolete)
191 // Adds an ACL entry for to deny modify access on the specified file for all users.
192 [Obsolete("DenyAccessRightModifyForUsers has been deprecated - define user access rights via SQL Server")]
193 public static void DenyAccessRightModifyForUsers(string fileName)
194 {
195 // Get a FileSecurity object that represents the current security settings.
196 FileSecurity fSecurity = File.GetAccessControl(fileName);
197
198 // Add FileSystemAccessRule:s to the security settings.
199 // Remote desktop users can read and write, but not delete
200 fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.Write, AccessControlType.Deny));
201 fSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.Modify, AccessControlType.Deny));
202
203 // Set the new access settings.
204 File.SetAccessControl(fileName, fSecurity);
205 }
206
207
208 // Writes config files to all of the TFTP directories definied in registry and database,
209 // and set rights.
210 public static void WriteConfigFiles(ATSImageRuntimeConfig config, string fileName, bool setRights)
211 { // config: The config that should be written to disk
212 // fileName: Name of the config file to write
213 // setRights: True = Set access rights on the file, so that all remote desktop users can delete the file.
214 // Write client config file
215
216 if (ATSGlobals.tftpConfig == 0)
217 { // Use ATS TFTP
218 WriteConfigFile(config, ATSGlobals.strTFTPdir + @"\" + fileName, setRights);
219 }
220 else if (ATSGlobals.tftpConfig == 1)
221 { // External TFTP
222 // Write the config file to all TFTP directories
223 atsDataSet.TftpServerDataTable datatableTFTP; // TFTP server directories
224 atsDataSetTableAdapters.TftpServerTableAdapter tftpServerTableAdapter; // The AnywhereTS application data adapter for the TFTP servers table. Only this adapter should be used.
225
226 tftpServerTableAdapter = new AnywhereTS.atsDataSetTableAdapters.TftpServerTableAdapter();
227 datatableTFTP = new atsDataSet.TftpServerDataTable();
228
229 tftpServerTableAdapter.Fill(datatableTFTP);
230 foreach (DataRow row in datatableTFTP.Rows)
231 {
232 WriteConfigFile(config, GetTftpPath(row) + @"\" + fileName, setRights);
233 }
234 }
235 else
236 {
237 string error = "Error: Unknown TFTP Config mode (28158)";
238 using (log4net.NDC.Push(string.Format("tftpConfig={0}", ATSGlobals.tftpConfig)))
239 {
240 Logging.ATSAdminLog.Error(error);
241 }
242 MessageBox.Show(string.Format("{0} -> {1}", error, string.Format("tftpConfig={0}", ATSGlobals.tftpConfig)));
243 return;
244 }
245 }
246
247 // Copy image file to all external tftp directories/servers
248 public static void CopyImageFile(string path, string sourceFileName, string destFileName)
249 {
250 atsDataSet.TftpServerDataTable datatableTFTP; // TFTP server directories
251 datatableTFTP = new atsDataSet.TftpServerDataTable();
252 atsDataSetTableAdapters.TftpServerTableAdapter tftpServerTableAdapter; // The AnywhereTS application data adapter for the TFTP servers table. Only this adapter should be used.
253 tftpServerTableAdapter = new AnywhereTS.atsDataSetTableAdapters.TftpServerTableAdapter();
254
255 tftpServerTableAdapter.Fill(datatableTFTP);
256 foreach (DataRow row in datatableTFTP.Rows)
257 {
258 // Copy to the TFTP server
259 try
260 {
261 File.Copy(path + @"\" + sourceFileName, GetTftpPath(row) + @"\" + destFileName, true);
262 }
263 catch (Exception e)
264 {
265 MessageBox.Show("Could not update TFTP server '" + GetTftpPath(row) + "' (22181). Error: " + e.Message);
266 using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", e.Message, System.Environment.NewLine, e.ToString())))
267 {
268 using (log4net.NDC.Push(string.Format("tftpPath={0}", GetTftpPath(row))))
269 {
270 Logging.ATSAdminLog.Error("Could not update TFTP server");
271 }
272 }
273 }
274
275 // Try to set rights for image the image file
276 // (not implemented)
277 /*
278 try
279 {
280 DenyAccessRightModifyForUsers(row["Path"].ToString() + @"\" + file);
281 }
282 catch (Exception e)
283 {
284 MessageBox.Show("Could not set rights for image file on TFTP server '" + row["Path"].ToString() + "' (22183). Error: " + e.Message);
285 } */
286 }
287 }
288
289 // Create subdirectory in all external tftp directories/servers
290 public static void CreateDirectoryOnTFTP_servers(string directoryName)
291 {
292 atsDataSet.TftpServerDataTable datatableTFTP; // TFTP server directories
293 datatableTFTP = new atsDataSet.TftpServerDataTable();
294 atsDataSetTableAdapters.TftpServerTableAdapter tftpServerTableAdapter; // The AnywhereTS application data adapter for the TFTP servers table. Only this adapter should be used.
295 tftpServerTableAdapter = new AnywhereTS.atsDataSetTableAdapters.TftpServerTableAdapter();
296
297 tftpServerTableAdapter.Fill(datatableTFTP);
298 foreach (DataRow row in datatableTFTP.Rows)
299 {
300 // Create the Directory on the TFTP server
301 try
302 {
303 Directory.CreateDirectory(GetTftpPath(row) + @"\" + directoryName);
304 }
305 catch (Exception e)
306 {
307 MessageBox.Show("Could not update TFTP server '" + GetTftpPath(row) + "' (22381). Error: " + e.Message);
308 using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", e.Message, System.Environment.NewLine, e.ToString())))
309 {
310 using (log4net.NDC.Push(string.Format("tftpPath={0}", GetTftpPath(row))))
311 {
312 Logging.ATSAdminLog.Error("Could not update TFTP server");
313 }
314 }
315 }
316 }
317 }
318
319 public static void WriteConfigFile(ATSImageRuntimeConfig config, string path, bool setRights)
320 {
321 config.WriteConfigFile(path);
322
323 if (setRights)
324 {
325 // Set access rights for the config file.
326 try
327 {
328 // Add an access control entry to the config file.
329 ProSupport.GrantRWMaccessForRemoteDesktopUsers(path);
330 }
331 catch (Exception ex)
332 {
333 MessageBox.Show("Cannot set access rights for client configuration. Application will abort. Error: " + ex.Message);
334 using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", ex.Message, System.Environment.NewLine, ex.ToString())))
335 {
336 Logging.ATSAdminLog.Error("Cannot set access rights for client configuration");
337 }
338 Application.Exit();
339 return;
340 }
341 }
342 }
343
344
345 // Writes host files to all of the TFTP directories definied in registry and database.
346 public static void WriteHostsFiles()
347 {
348 if (ATSGlobals.tftpConfig == 0)
349 { // Use ATS TFTP
350 WriteHostsFile(ATSGlobals.strTFTPdir + @"\" + strHostsFilename);
351 }
352 else if (ATSGlobals.tftpConfig == 1)
353 { // External TFTP
354 // Write the config file to all TFTP directories
355 atsDataSet.TftpServerDataTable datatableTFTP; // TFTP server directories
356 datatableTFTP = new atsDataSet.TftpServerDataTable();
357 tftpServerTableAdapter.Fill(datatableTFTP);
358 foreach (DataRow row in datatableTFTP.Rows)
359 {
360 WriteHostsFile(GetTftpPath(row) + @"\" + strHostsFilename);
361 }
362 }
363 else
364 {
365 string error = "Error: Unknown TFTP Config mode (48158)";
366 using (log4net.NDC.Push(string.Format("tftpConfig={0}", ATSGlobals.tftpConfig)))
367 {
368 Logging.ATSAdminLog.Error(error);
369 }
370 MessageBox.Show(string.Format("{0} -> {1}", error, string.Format("tftpConfig={0}", ATSGlobals.tftpConfig)));
371 return;
372 }
373 }
374
375
376 // Create a (new) encrypted hosts file from data in the database.
377 private static void WriteHostsFile(string path)
378 {
379 atsDataSet datasetClient = new atsDataSet();
380 ProSupport.clientTableAdapter.FillClients(datasetClient.Client);
381
382 // System.IO.StreamWriter writer = null;
383 CryptStream writer = null;
384
385 // Delete old hosts file
386 if (System.IO.File.Exists(path))
387 {
388 System.IO.File.Delete(path);
389 }
390
391 // Write a new hosts file.
392 try
393 {
394 //writer = new System.IO.StreamWriter(path);
395 writer = new CryptStream(path);
396 writer.NewLine = "\n"; // Unix style line terminators
397 writer.WriteLine("# This is a hosts file generated by AnywhereTS. Do not change.");
398 foreach (DataRow row in datasetClient.Client.Rows)
399 {
400 writer.WriteLine(row["ClientName"].ToString() + " " + row["MacAddress"].ToString());
401 }
402 writer.WriteLine("# Detta e slutet."); // Termination string to avoid decryptation bug.
403 }
404 catch (Exception e)
405 {
406 //improve autoretry
407 MessageBox.Show("Error: Could not write configuration data to disk. Possibly the data is being accessed by another component right now or you do not have the sufficient rights. Please retry this operation later (52044). Error details: " + e.Message);
408 using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", e.Message, System.Environment.NewLine, e.ToString())))
409 {
410 using (log4net.NDC.Push(string.Format("path={0}", path)))
411 {
412 Logging.ATSAdminLog.Error("Could not write configuration data to disk");
413 }
414 }
415 }
416
417 finally
418 {
419 if (writer != null)
420 writer.Close();
421 }
422
423 // DenyAccessRightModifyForUsers(path); // Prevent users from deleting or modifying the hosts file.
424 }
425
426
427 // Check if user is administrator
428 // Returns true if user is administrator
429 public static bool IsAnAdministrator()
430 {
431 WindowsIdentity identity =
432 WindowsIdentity.GetCurrent();
433 WindowsPrincipal principal =
434 new WindowsPrincipal(identity);
435 return principal.IsInRole
436 (WindowsBuiltInRole.Administrator);
437 }
438
439 public static string GetMacAddressFromNameAndDatabase(string strName)
440 {
441 string macAddress;
442 // Try to extract MAC address from client name.
443 macAddress = ATSGlobals.GetMacFromATSname(strName);
444 if (macAddress.Length == 0)
445 { // MAC not in name, try to lookup client name in database
446 atsDataSet datasetClientName = new atsDataSet();
447 // Update dataset with the client row matching the name
448 try
449 {
450 ProSupport.clientTableAdapter.FillOnName(datasetClientName.Client, strName);
451 }
452 catch
453 { // Error when accessing database
454 return "";
455 }
456 if (datasetClientName.Client.Rows.Count > 0)
457 { // Client row found in database
458 macAddress = datasetClientName.Client.Rows[0]["MacAddress"].ToString();
459 }
460 else
461 { // Name not found
462 macAddress = "";
463 }
464 }
465 return macAddress;
466 }
467
468 // Re-writes all config files, so that they will be containing new parameters.
469 // Also creates config files if they have been deleted, i.e by an expired beta.
470 public static void RecreateConfigFiles()
471 {
472 // Re-create all config files
473 if (ATSGlobals.tftpConfig == 0)
474 { // Use ATS TFTP
475 WriteConfigFiles(ATSGlobals.strTFTPdir);
476 }
477 else if (ATSGlobals.tftpConfig == 1)
478 { // External TFTP
479 // Write the config file to all TFTP directories
480 atsDataSet.TftpServerDataTable datatableTFTP; // TFTP server directories
481 datatableTFTP = new atsDataSet.TftpServerDataTable();
482 tftpServerTableAdapter.Fill(datatableTFTP);
483 foreach (DataRow row in datatableTFTP.Rows)
484 {
485 // Write to TFTP path
486 WriteConfigFiles(GetTftpPath(row));
487 }
488 }
489 else
490 {
491 string error = "Error: Unknown TFTP Config mode (88158)";
492 using (log4net.NDC.Push(string.Format("tftpConfig={0}", ATSGlobals.tftpConfig)))
493 {
494 Logging.ATSAdminLog.Error(error);
495 }
496 MessageBox.Show(string.Format("{0} -> {1}", error, string.Format("tftpConfig={0}", ATSGlobals.tftpConfig)));
497 return;
498 }
499
500 WriteHostsFiles();
501 ATSImageRuntimeConfig currentConfig = new ATSImageRuntimeConfig();
502 currentConfig.ReadDefaultFromDatabase();
503 ProSupport.WriteConfigFiles(currentConfig, ProSupport.strNetworkConfigFilename, false);
504 }
505
506
507 static void WriteConfigFiles(string strDirectory)
508 {
509 ATSImageRuntimeConfig currentConfig = new ATSImageRuntimeConfig();
510 atsDataSet datasetClient = new atsDataSet();
511 ProSupport.clientTableAdapter.FillClients(datasetClient.Client);
512 string strFilePath;
513 foreach (DataRow row in datasetClient.Client.Rows)
514 {
515 // Write the config file corresponding to the client
516 currentConfig.ReadFromDatabase(row);
517 strFilePath = strDirectory + @"\" + row["MacAddress"];
518 currentConfig.WriteConfigFile(strFilePath);
519 }
520 }
521
522 // Return a local or UNC path for TFTP server, depending on what it best.
523 public static string GetTftpPath(DataRow tftpRow)
524 {
525 // Extract computer name from UNC Path
526 string uncPath = tftpRow["Path"].ToString();
527 string uncComputer = uncPath.Substring(2, uncPath.IndexOf(@"\", 2) - 2);
528 if (uncComputer.ToUpper() == Environment.MachineName)
529 { // The UNC path resides on this computer, use a local path if it is available
530 if (tftpRow["LocalPath"].ToString().Length > 0)
531 { // We have a local path
532 return tftpRow["LocalPath"].ToString();
533 }
534 else
535 { // No local path, we have to go with the UNC path referring to the local machine.
536 return tftpRow["Path"].ToString();
537 }
538 }
539 else
540 { // The UNC path does not reside on this computer, use it as it is.
541 return tftpRow["Path"].ToString();
542 }
543 }
544
545
546 // Sub routines used by wizard for screen resolution
547 //-----------------------------------------------------
548
549 public static void UpdateScreenResolutionControls(int x, int y, TextBox txtScreenResX, TextBox txtScreenResY, TrackBar tbrScreenResolution)
550 {
551 txtScreenResX.Text = x.ToString();
552 txtScreenResY.Text = y.ToString();
553
554 for (int i = 0; i < ATSGlobals.ScreenResolutions.GetLength(0); i++)
555 {
556 if (x == ATSGlobals.ScreenResolutions[i, 0] && y == ATSGlobals.ScreenResolutions[i, 1])
557 {
558 tbrScreenResolution.Value = i + 1;
559 return;
560 }
561
562 }
563 // Values could not be expressed using the track bar. Set it at default.
564 tbrScreenResolution.Value = 4;
565 }
566
567 public static void GetScreenResolutionFromTrackbar(TrackBar tbr, out int x, out int y)
568 {
569 x = ATSGlobals.ScreenResolutions[tbr.Value - 1, 0];
570 y = ATSGlobals.ScreenResolutions[tbr.Value - 1, 1];
571 }
572
573 public static void UpdateResolutionTrackbar(TextBox txtScreenResX, TextBox txtScreenResY, TrackBar tbrScreenResolution)
574 { // Try to convert x, y values to trackbar.
575 int x, y;
576 try
577 {
578 x = Int32.Parse(txtScreenResX.Text.Trim());
579 }
580 catch (Exception)
581 {
582 x = 0;
583 }
584
585 try
586 {
587 y = Int32.Parse(txtScreenResY.Text.Trim());
588 }
589 catch (Exception)
590 {
591 y = 0;
592 }
593
594 UpdateScreenResolutionControls(x, y, txtScreenResX, txtScreenResY, tbrScreenResolution);
595 }
596
597
598
599 public static void copyDirectory(string Src,string Dst)
600 {
601 String[] Files;
602
603 if(Dst[Dst.Length-1]!=Path.DirectorySeparatorChar)
604 Dst+=Path.DirectorySeparatorChar;
605 if(!Directory.Exists(Dst)) Directory.CreateDirectory(Dst);
606 Files=Directory.GetFileSystemEntries(Src);
607 foreach(string Element in Files){
608 // Sub directories
609
610 if(Directory.Exists(Element))
611 copyDirectory(Element,Dst+Path.GetFileName(Element));
612 // Files in directory
613
614 else
615 File.Copy(Element,Dst+Path.GetFileName(Element), true);
616 }
617 }
618
619
620
621
622 } // end class Prosupport
623
624
625 public class CryptStream : StreamWriter
626 {
627 BinaryWriter outStream;
628
629 const byte offset1 = 36;
630 const byte offset2 = 0xab;
631 const byte key = 0x36;
632 byte value;
633
634 public CryptStream(string s)
635 : base(s)
636 {
637 // Base constructor has created a stream. Steal it.
638 outStream = new BinaryWriter(base.BaseStream);
639 WriteHeader();
640 }
641
642
643 public CryptStream(Stream s)
644 : base(s)
645 {
646 outStream = new BinaryWriter(s);
647 WriteHeader();
648 }
649
650
651 private void WriteHeader()
652 {
653 outStream.Write((byte)0x41);
654 outStream.Write((byte)0x54);
655 outStream.Write((byte)0x53);
656 outStream.Write((byte)0x78);
657 value = key;
658 }
659
660
661 private byte Crypt(byte ch1)
662 {
663 byte ch2 = (byte)((ch1 + offset1) & 0xFF);
664 byte ch3 = (byte)((ch2 ^ value) & 0xFF);
665 value = (byte)((value + offset2) & 0xFF);
666 return ch3;
667 }
668
669 public override void Write(string s)
670 {
671 for (int i = 0; i < s.Length; i++)
672 outStream.Write(Crypt((byte)s[i]));
673 }
674
675
676 public override void WriteLine(string s)
677 {
678 Write(s);
679 Write("\n");
680 }
681 }
682
683 } //end namespace