/// <summary> /// Save the user settings to a persistent data store. /// </summary> private static void LocalWrite() { IsolatedStorageFileStream isolatedStorageFileStream = null; try { // Create the document that will hold the application settings. IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForAssembly(); // Create the document that will hold the application settings. isolatedStorageFileStream = new IsolatedStorageFileStream(profileFileName, FileMode.Create, FileAccess.Write, FileShare.None, isolatedStorageFile); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(isolatedStorageFileStream, UserPreferences.localSettings); } catch (Exception exception) { EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace); } finally { if (isolatedStorageFileStream != null) { isolatedStorageFileStream.Close(); } } }
/// <summary> /// Parses a section of the configuration file for information about the persistent stores. /// </summary> /// <param name="parent">The configuration settings in a corresponding parent configuration section.</param> /// <param name="configContext">An HttpConfigurationContext when Create is called from the ASP.NET configuration system. /// Otherwise, this parameter is reserved and is a null reference.</param> /// <param name="section">The XmlNode that contains the configuration information from the configuration file. Provides direct access to the XML contents of the configuration section.</param> /// <returns>A ViewerSection object created from the data in the configuration file.</returns> public object Create(object parent, object configContext, System.Xml.XmlNode section) { // Create an object to hold the data from the 'viewer' section of the application configuration file. ViewerSection viewerSection = new ViewerSection(); try { // Read each of the nodes that contain information about the persistent stores and place them in the table. foreach (XmlNode xmlNode in section.SelectNodes("add")) { // The 'type' section of the configuration file is modeled after other places in the OS where the type and // assembly information are combined in the same string. A simpler method might have been to break aprart the // type string from the assembly string, but it's also a good idea to use standards where you find them. In // any event, when the 'type' specification is done this way, the padded spaces need to be removed from the // values onced they're broken out from the original string. string typeSpecification = xmlNode.Attributes["type"].Value; if (typeSpecification == null) { throw new Exception("Syntax error in configuration file section 'viewers'."); } string[] typeParts = typeSpecification.Split(new char[] { ',' }); if (typeParts.Length != 2) { throw new Exception("Syntax error in configuration file section 'viewers'."); } Assembly typeAssembly = Assembly.Load(typeParts[ViewerSectionHandler.AssemblyIndex].Trim()); Type typeType = typeAssembly.GetType(typeParts[ViewerSectionHandler.TypeIndex]); string viewerSpecification = xmlNode.Attributes["viewer"].Value; if (viewerSpecification == null) { throw new Exception("Syntax error in configuration file section 'viewers'."); } string[] viewerParts = viewerSpecification.Split(new char[] { ',' }); if (viewerParts.Length != 2) { throw new Exception("Syntax error in configuration file section 'viewers'."); } Assembly viewerAssembly = Assembly.Load(viewerParts[ViewerSectionHandler.AssemblyIndex].Trim()); Type viewerType = viewerAssembly.GetType(viewerParts[ViewerSectionHandler.TypeIndex]); // Add the viewer information to the section. Each of these ViewerInfo items describes what kind of object the // viewer is associated with and where to find the viewer. viewerSection.Add(new ViewerInfo(typeType, viewerType)); } } catch (Exception exception) { // Make sure that any errors caught while trying to load the viewer info is recorded in the log. A system // administrator can look through these to figure out why the viewer information isn't formatted correctly. EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace); } // This object can be used to find a persistent store by nane and connect to it. return(viewerSection); }
public WebPage(params object[] parameter) { try { // Initialize the object. this.Uri = new System.Uri((string)parameter[0]); } catch (Exception exception) { EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace); } }
/// <summary> /// Play the sound specified by the .WAV file sent as a parameter. /// </summary> /// <param name="filename">The name of the .WAV file to play.</param> public static void PlaySound(string filename) { try { // Play the sound from the filename. PlaySound(filename, 0L, 0x0001 | 0x00020000); } catch (Exception exception) { // Throw any error messages out to the debug listener. EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace); } }
/// <summary> /// Play a system sound /// </summary> /// <param name="sound"></param> public static void PlaySound(uint sound) { try { // Play the sound from the operating system. MessageBeep(sound); } catch (Exception exception) { // Throw any error messages out to the debug listener. EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace); } }
static TransactionProtocol() { try { // The PersistentStoreSection contains information about what databases and other 'persistent' storage is // available. For example, an SQL Database would have a unique short name, used to identify the database, and a // connection string. This data would be used to establish a connection to the store for queries, inserts, updates // and deletes. Each library class that can participate in a transaction to this store will specify the short name // of the store in a 'PersistentStore' field. TransactionProtocol.resourceDescriptionList = (List <ResourceDescription>)ConfigurationManager.GetSection("resourceSection"); } catch (Exception exception) { // Any problems initializing should be sent to the Event Log. EventLog.Error("{0}: {1}", exception.Message, exception.StackTrace); } }
static public object Compile(MetaAssembly metaAssembly, params object[] parameters) { object instance = null; CSharpCodeProvider cSharpCodeProvider = new CSharpCodeProvider(); CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.OutputAssembly = metaAssembly.OutputAssembly; compilerParameters.TreatWarningsAsErrors = metaAssembly.TreatWarningsAsErrors; compilerParameters.WarningLevel = metaAssembly.WarningLevel; compilerParameters.GenerateExecutable = metaAssembly.GenerateExecutable; compilerParameters.CompilerOptions = metaAssembly.CompilerOptions; compilerParameters.GenerateInMemory = metaAssembly.GenerateInMemory; compilerParameters.IncludeDebugInformation = metaAssembly.IncludeDebugInformation; if (metaAssembly.Dependancies != null && metaAssembly.Dependancies.Length != 0) { compilerParameters.ReferencedAssemblies.AddRange(metaAssembly.Dependancies); } // Invoke compilation. CompilerResults compilerResults = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, metaAssembly.SourceCode); if (compilerResults.Errors.Count > 0) { foreach (CompilerError compilerError in compilerResults.Errors) { EventLog.Error("{0}: {1}", compilerParameters.OutputAssembly, compilerError.ToString()); } } else { instance = compilerResults.CompiledAssembly.CreateInstance(metaAssembly.OutputType, false, BindingFlags.CreateInstance, null, parameters, CultureInfo.InvariantCulture, null); } if (compilerResults.Errors.Count > 0) { throw new Exception(string.Format("Module {0} had {1} compilation errors", compilerParameters.OutputAssembly, compilerResults.Errors.Count)); } return(instance); }
/// <summary> /// Save the user settings to a persistent data store. /// </summary> private static void GlobalWrite() { try { // MemoryStream memoryStream = new MemoryStream(); // BinaryFormatter binaryFormatter = new BinaryFormatter(); // binaryFormatter.Serialize(memoryStream, UserPreferences.globalSettings); // // FileStream fileStream = new FileStream("SettingsTest", FileMode.OpenOrCreate, FileAccess.Write); // BinaryWriter binaryWriter = new BinaryWriter(fileStream); // byte[] settingStream = memoryStream.GetBuffer(); // binaryWriter.Write(settingStream.Length); // binaryWriter.Write(settingStream); // binaryWriter.Close(); } catch (Exception exception) { EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace); } }
/// <summary> /// Load the settings from the local persistent store. /// </summary> private static void GlobalRead() { try { // FileStream fileStream = new FileStream("SettingsTest", FileMode.Open, FileAccess.Read); // BinaryReader binaryReader = new BinaryReader(fileStream); // int streamSize = binaryReader.ReadInt32(); // Byte[] settingStream = binaryReader.ReadBytes(streamSize); // binaryReader.Close(); // // MemoryStream memoryStream = new MemoryStream(settingStream); // BinaryFormatter binaryFormatter = new BinaryFormatter(); // UserPreferences.globalSettings = (Hashtable)binaryFormatter.Deserialize(memoryStream); // memoryStream.Close(); } catch (Exception exception) { EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace); } }
/// <summary> /// Executes a batch of commands as a series of transactions that are committed or rejected as a unit. /// </summary> static BatchProcessor() { try { // The 'resourceSection' section of the configuration file contains about the resource managers available for the // transaction processor. Volatile Resource Managers provide an API and housekeeping data for managing the memory // based data while the Durable Resource Managers govern the handling of the data that resides on a disk // somewhere. This section of the configuration file describes the resource managers available and their // properties. BatchProcessor.resourceDescriptionList = (List <ResourceDescription>)ConfigurationManager.GetSection("resourceSection"); // This will read through each of the descriptions of the resource managers found in the configuratino file and // initialize the static properties. foreach (ResourceDescription resourceDescription in BatchProcessor.resourceDescriptionList) { if (resourceDescription is SqlResourceDescription) { SqlResourceDescription sqlResourceDescription = resourceDescription as SqlResourceDescription; SqlResourceManager.AddConnection(sqlResourceDescription.Name, sqlResourceDescription.ConnectionString); } } // This will read through each of the descriptions of the resource managers found in the configuratino file and // initialize the static properties. foreach (ResourceDescription resourceDescription in BatchProcessor.resourceDescriptionList) { if (resourceDescription is AdoResourceDescription) { AdoResourceDescription adoResourceDescription = resourceDescription as AdoResourceDescription; MethodInfo methodInfo = adoResourceDescription.Type.GetMethod("GetDataSet"); AdoResourceManager.AddDataSet(adoResourceDescription.Name, methodInfo.Invoke(null, null) as DataSet); } } } catch (Exception exception) { // Any problems initializing should be sent to the Event Log. EventLog.Error("{0}: {1}", exception.Message, exception.StackTrace); } }
/// <summary> /// Load the settings from the local persistent store. /// </summary> private static void LocalRead() { IsolatedStorageFileStream isolatedStorageFileStream = null; UserPreferences.localSettings = new Hashtable(); try { // See if a file already exists with the user's preferences. The scope of the isolated store is the 'Batch.Assembly' level, which means that // any code using this class will share the same settings. IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForAssembly(); if (isolatedStorageFile.GetFileNames(profileFileName).Length != 0) { // Open the "User Preferences" store for this application/user combination. isolatedStorageFileStream = new IsolatedStorageFileStream(profileFileName, FileMode.Open, FileAccess.Read, FileShare.None, isolatedStorageFile); BinaryFormatter binaryFormatter = new BinaryFormatter(); UserPreferences.localSettings = (Hashtable)binaryFormatter.Deserialize(isolatedStorageFileStream); } } catch (Exception exception) { UserPreferences.localSettings.Clear(); EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace); } finally { if (isolatedStorageFileStream != null) { isolatedStorageFileStream.Close(); } } }
/// <summary> /// Execute the batch on the Web Transaction server and return the results to the caller. /// </summary> /// <param name="batch">Contains one or more transactions that are executed on the server. The results of executing the /// batch are returned to the caller in this object.</param> Result IBatchHandler.Execute(Batch batch) { Result batchResult = null; // These streams must be shut down, even when an exception is taken. They are declared here so they can be accessed by // the 'finally' clause should something go wrong. Stream requestStream = null; WebResponse webResponse = null; Stream responseStream = null; try { // The client communicates the 'batch' data structure to the server using an HTTP channel. The channel is // configured to use SSL and Certificates to insure the privacy of the conversation. WebRequest webRequest = CreateCertificateRequest(); // The 'batch' data structure is serialized and compressed before being sent to the server. MemoryStream memoryStreamRequest = new MemoryStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(memoryStreamRequest, batch); // This section will compress the serial stream. Note that it must be compressed into an intermediate buffer // before being sent via the HttpWebRequest class because the number of bytes must be known before the call is made // for the 'ContentLength' parameter of the HttpWebRequest object. memoryStreamRequest.Position = 0L; requestStream = webRequest.GetRequestStream(); DeflateStream requestDeflateStream = new DeflateStream(requestStream, CompressionMode.Compress, true); requestDeflateStream.Write(memoryStreamRequest.GetBuffer(), 0, (int)memoryStreamRequest.Length); requestDeflateStream.Close(); requestStream.Close(); // This is where all the work is done. Send the Request to the HTTP Server and get the response. In this // case, the response will be the results of executing the remote batch. Note that we get back only the // framework of the RPB, not all the parameters, methods, assemblies and types. This is an optimization so // that the same data isn't sent twice over the network. This 'differential' data will be merged with the // original. To the user, it appears that the Remote Batch.Method Batch was sent to the server, filled in with // result and exception data, then returned to the calling method. Actually, the batch was sent, the results // and exceptions returned, and it was all stitched back together again before the user gets it. webResponse = webRequest.GetResponse(); // Decompress the results from the HttpWebResponse stream. responseStream = webResponse.GetResponseStream(); DeflateStream responseDeflateStream = new DeflateStream(responseStream, CompressionMode.Decompress); byte[] uncompressedBuffer = CompressedStreamReader.ReadBytes(responseDeflateStream); responseDeflateStream.Close(); // Deserialize the batch results and merge it back with the original structure. The 'BatchResult' // structure has the same basic structure as the original batch, but only contains output parameters and // exceptions. MemoryStream memoryStreamResponse = new MemoryStream(uncompressedBuffer); BinaryFormatter binaryFormatterResponse = new BinaryFormatter(); batchResult = (Result)binaryFormatterResponse.Deserialize(memoryStreamResponse); memoryStreamResponse.Close(); } catch (WebException webException) { // The response in the exception usually indicates that we found the server, but the protocol failed for some // reason. When the response is empty, that usually indicates that the URL is bad or the server is down for // some reason. if (webException.Response == null) { // Log the error. EventLog.Error("Web Exception {0}, {1}", webException.Status, webException.Message); } else { // Extract the information sent back from the server and log it. webResponse = (HttpWebResponse)webException.Response; EventLog.Error(webException.Message); // Present the user with the error code. There may be a better way to do this, but this will work for now. MessageBox.Show(webException.Message, string.Format("{0} - {1}", Application.ProductName, Properties.Resources.ConnectionError)); } // Prompt the user for the URL and credentials again. HttpBatchProcessor.IsUrlPrompted = true; HttpBatchProcessor.IsCredentialPrompted = true; // This gives the caller a unified way to handle all exceptions that may have occurred while processing a batch. // The Web Exceptions are handled the same way as errors from the server. throw new BatchException(webException); } catch (UserAbortException) { // forward the exception so the caller can decide what to do. throw; } catch (Exception exception) { // This gives the caller a unified way to handle all exceptions that may have occurred while processing a batch. // The general exceptions are handled the same way as exceptions from the server. throw new BatchException(exception); } finally { // Make sure that every stream involved with the request is closed when the WebRequest is finished. if (requestStream != null) { requestStream.Close(); } if (responseStream != null) { responseStream.Close(); } if (webResponse != null) { webResponse.Close(); } } return(batchResult); }
/// <summary> /// Parses a section of the configuration file for information about the persistent stores. /// </summary> /// <param name="parent">The configuration settings in a corresponding parent configuration section.</param> /// <param name="configContext">An HttpConfigurationContext when Create is called from the ASP.NET configuration system. /// Otherwise, this parameter is reserved and is a null reference.</param> /// <param name="section">The XmlNode that contains the configuration information from the configuration file. Provides direct access to the XML contents of the configuration section.</param> /// <returns>A ToolSection object created from the data in the configuration file.</returns> public object Create(object parent, object configContext, System.Xml.XmlNode section) { // Create an object to hold the data from the 'tool' section of the application configuration file. ToolSection toolSection = new ToolSection(); try { // Read each of the nodes that contain information about the persistent stores and place them in the table. foreach (XmlNode xmlNode in section.SelectNodes("add")) { // The 'type' section of the configuration file is modeled after other places in the OS where the type and // assembly information are combined in the same string. A simpler method might have been to break aprart the // type string from the assembly string, but it's also a good idea to use standards where you find them. In // any event, when the 'type' specification is done this way, the padded spaces need to be removed from the // values onced they're broken out from the original string. XmlAttribute keyAttribute = xmlNode.Attributes["key"]; if (keyAttribute == null) { throw new Exception("Syntax error in configuration file section 'tools'."); } string name = keyAttribute.Value; // The text appears in the 'Tools' menu. XmlAttribute textAttribute = xmlNode.Attributes["text"]; if (textAttribute == null) { throw new Exception("Syntax error in configuration file section 'tools'."); } string text = textAttribute.Value; // Pull apart the tool specification from the attributes. XmlAttribute toolSpecificationAttribute = xmlNode.Attributes["tool"]; if (toolSpecificationAttribute == null) { throw new Exception("Syntax error in configuration file section 'tools'."); } string[] toolParts = toolSpecificationAttribute.Value.Split(new char[] { ',' }); if (toolParts.Length != 2) { throw new Exception("Syntax error in configuration file section 'tools'."); } // Attempt to load the tool into memory and find the type used to instantiate the tool. Assembly toolAssembly = Assembly.Load(toolParts[ToolSectionHandler.AssemblyIndex].Trim()); Type toolType = toolAssembly.GetType(toolParts[ToolSectionHandler.TypeIndex]); // Add the tool information to the section. Each of these ToolInfo items describes what kind of object the // tool is associated with and where to find the tool. toolSection.Add(new ToolInfo(name, text, toolType)); } } catch (Exception exception) { // Make sure that any errors caught while trying to load the tool info is recorded in the log. A system // administrator can look through these to figure out why the tool information isn't formatted correctly. EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace); } // This object can be used to find a persistent store by nane and connect to it. return(toolSection); }