C #10 practical codes frequently encountered in program development

Source: Internet
Author: User

1. Read the operating System and CLR versions OperatingSystem OS = System. environment. OSVersion; Console. writeLine ("Platform: {0}", OS. platform); Console. writeLine ("ServicePack: {0}", OS. servicePack); Console. writeLine ("Version: {0}", OS. version); Console. writeLine ("VersionString: {0}", OS. versionString); Console. writeLine ("CLRVersion: {0}", System. environment. in my Windows 7 system, the following information is output: Platform: Win32NT Service Pack: Version: 6.1.7600.0 VersionString: Number of CPUs read by Microsoft Windows NT 6.1.7600.0 CLR Version: 4.0.21006.1 2. The memory capacity can be read through the interface provided by Windows Management Instrumentation (WMI. Private static UInt32CountPhysicalProcessors () {ManagementObjectSearcher objects = new ManagementObjectSearcher ("SELECT * FROM Win32_ComputerSystem"); ManagementObjectCollection coll = objects. get (); foreach (ManagementObject obj in coll) {return (UInt32) obj ["NumberOfProcessors"];} return 0;} private static events () {ManagementObjectSearcher objects = new ManagementObjectSear Cher ("SELECT * FROM Win32_PhysicalMemory"); ManagementObjectCollection coll = objects. get (); UInt64 total = 0; foreach (ManagementObject obj in coll) {total + = (UInt64) obj ["Capacity"];} return total ;} add the assembly System. management to ensure that the code can be correctly compiled. Console. writeLine ("Machine: {0}", Environment. machineName); Console. writeLine ("# of processors (logical): {0}", Environment. processorCount); Console. writeLine ("# of processors (physical): {0}" CountPhysicalProcessors (); Console. writeLine ("RAMinstalled: {0: N0} bytes", CountPhysicalMemory (); Console. writeLine ("IsOS 64-bit? {0} ", Environment. Is64BitOperatingSystem); Console. WriteLine (" Isprocess 64-bit? {0} ", Environment. is64BitProcess); Console. writeLine ("Little-endian: {0}", BitConverter. isLittleEndian); foreach (Screen screen in System. windows. forms. screen. allScreens) {Console. writeLine ("Screen {0}", screen. deviceName); Console. writeLine ("\ tPrimary {0}", screen. primary); Console. writeLine ("\ tBounds: {0}", screen. bounds); Console. writeLine ("\ tWorking Area: {0}", screen. workingArea); Console. writeLin E ("\ tBitsPerPixel: {0}", screen. bitsPerPixel);} 3 read the using (RegistryKey keyRun = Registry. localMachine. openSubKey (@ "Software \ Microsoft \ Windows \ CurrentVersion \ Run") {foreach (string valueName in keyRun. getValueNames () {Console. writeLine ("Name: {0} \ tValue: {1}", valueName, keyRun. getValue (valueName);} Add the namespace Microsoft. win32 to ensure that the above Code can be compiled. 4. Start and Stop the Windows service. This API provides a practical function that is often used to manage services in applications without having to perform operations in the management service of the control panel. ServiceControllercontroller = new ServiceController ("e-M-POWER"); controller. start (); if (controller. canPauseAndContinue) {controller. pause (); controller. continue ();} controller. stop ();. net API, you can install and uninstall the service in one sentence if (args [0] = "/I") {ManagedInstallerClass. installHelper (new string [] {Assembly. getExecutingAssembly (). location});} else if (args [0] = "/u") {ManagedInstallerClass. installHelper (n Ew string [] {"/u", Assembly. getExecutingAssembly (). location});} as shown in the code, input an I or u parameter to the application to uninstall or install the application. 5. Check whether the program has strong name (P/Invoke). For example, to verify whether the Assembly has a signature, call the following method [DllImport ("mscoree. dll ", CharSet = CharSet. unicode)] static extern bool evaluate (string wszFilePath, bool fForceVerification, ref bool pfWasVerified); bool notForced = false; bool verified = compile (assembly, false, ref notForced); Console. writeLine ("Verified: {0} \ nForced: {1}", verified ,! NotForced); this feature is commonly used in software protection methods and can be used to verify signature components. Even if your signature is removed or all the Assembly signatures are removed, you can stop running the program as long as this call code exists in the program. 6. Respond to system configuration item changes. For example, if QQ does not exit after the system is locked, the system will be busy. Add the namespace Microsoft. Win32 and register the following events.. DisplaySettingsChanged (including Changing) display settings. installedFontsChanged font change. paletteChanged. powerModeChanged Power status. sessionEnded (the user is logging out or the session ends ). sessionSwitch (Change current user ). time changed. userPreferenceChanged our ERP system will monitor whether the system time has changed. If the time is adjusted beyond the ERP license file, the ERP software will become unavailable. 7. Use the new features of Windows 7 to introduce some new features. For example, in the open file dialog box, the status bar displays the progress of the current task. Microsoft. windowsAPICodePack. dialogs. commonOpenFileDialogofd = new Microsoft. windowsAPICodePack. dialogs. commonOpenFileDialog (); ofd. addToMostRecentlyUsedList = true; ofd. isFolderPicker = true; ofd. allowNonFileSystemItems = true; ofd. showDialog (); use this method to open the dialog box. It has more functions than OpenFileDialog in the class library that comes with BCL. However, it is only in Windows 7, so to call this code, check that the OS version is greater than 6, and add the Windows API CodePack for Microsoft®. NET Framework reference, please download the http://code.msdn.microsoft.com/WindowsAPICodePack 8 check program memory consumption using the following method, you can check. NET to allocate the program the amount of memory long available = GC. getTotalMemory (false); Console. writeLine ("Beforeallocations: {0: N0}", available); int allocSize = 40000000; byte [] bigArray = new byte [allocSize]; available = GC. getTotalMemory (false); Console. writeLine ("Afterallocations: {0: N0}", available); in my system, it runs as follows: Befor Eallocations: 651,064 After allocations: 40,690,080 use the following method to check the memory occupied by the current application Process proc = Process. getCurrentProcess (); Console. writeLine ("ProcessInfo:" + Environment. newLine + "Private Memory Size: {0: N0}" + Environment. newLine + "Virtual MemorySize: {1: N0}" + Environment. newLine + "Working Set Size: {2: N0}" + Environment. newLine + "Paged Memory Size: {3: N0}" + Environment. newLine + "Paged SystemMemory Si Ze: {4: N0} "+ Environment. newLine + "Non-paged System Memory Size: {5: N0}" + Environment. newLine, proc. privateMemorySize64, proc. virtualMemorySize64, proc. workingSet64, proc. pagedMemorySize64, proc. pagedSystemMemorySize64, proc. nonpagedSystemMemorySize64); 9 use the StopWatch to check the running time. If you are worried that some code is very time-consuming, you can use StopWatch to check the time consumed by this Code, as shown in the following code: System. diagnostics. stopwatchtimer = new System. diagnostics. stopwatch (); timer. Start (); Decimal total = 0; int limit = 1000000; for (int I = 0; I <limit; ++ I) {total = total + (Decimal) Math. sqrt (I);} timer. stop (); Console. writeLine ("Sumof sqrts: {0}", total); Console. writeLine ("Elapsedmilliseconds: {0}", timer. elapsedMilliseconds); Console. writeLine ("Elapsedtime: {0}", timer. elapsed); now there is a dedicated tool to detect the running time of the program, which can be refined to every method, such as the dotNetPerformance software. The above code is an example. You need to directly modify the source code. It is inconvenient to test the program. See the following example. Class AutoStopwatch: System. diagnostics. stopwatch, IDisposable {public AutoStopwatch () {Start ();} public void Dispose () {Stop (); Console. writeLine ("Elapsed: {0}", this. elapsed) ;}}with the help of the using syntax, as shown in the following code, you can check the running time of a piece of code and print it on the console. Using (new AutoStopwatch () {Decimal total2 = 0; int limit2 = 1000000; for (int I = 0; I <limit2; ++ I) {total2 = total2 + (Decimal) Math. sqrt (I) ;}10 use the cursor to change the cursor status to busy when the program is running and saved in the background or the volume division operation. You can use the following tips. Class AutoWaitCursor: IDisposable {private Control _ target; private Cursor _ prevCursor = Cursors. default; public AutoWaitCursor (Control control) {if (control = null) {throw newArgumentNullException ("control");} _ target = control; _ prevCursor = _ target. cursor; _ target. cursor = Cursors. waitCursor;} public void Dispose () {_ target. the usage of Cursor = _ prevCursor;} is as follows, in order to predict that the program may throw an exception using (ne W AutoWaitCursor (this) {... throw new Exception ();} as shown in the Code, the cursor can be restored even if an Exception is thrown.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.