ViewVC Help
View File | Revision Log | Show Annotations | Download File | View Changeset | Root Listing
root/AnywhereTS-MSSQL/trunk/TSAdminTool/ProSupport.cs
Revision: 91
Committed: Sat Jul 14 00:36:23 2012 UTC (11 years, 2 months ago) by william
File size: 31026 byte(s)
Log Message:

File Contents

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