10 practical code C # developers often encountered

1 read the operating system and the CLR version

OperatingSystem os = System.Environment.OSVersion;

Console.WriteLine(“Platform: {0}”, os.Platform);

Console.WriteLine(“Service Pack: {0}”, os.ServicePack);

Console.WriteLine(“Version: {0}”, os.Version);

Console.WriteLine(“VersionString: {0}”, os.VersionString);

Console.WriteLine(“CLR Version: {0}”, System.Environment.Version);

 

 

In my Windows 7 system, the output of the following information

Platform: Win32NT 
Service Pack: 
Version: 6.1.7600.0 
VersionString: Microsoft Windows NT 6.1.7600.0 
CLR Version: 4.0.21006.1

 

2 reads the CPU number, memory capacity

The interface can read Windows Management Instrumentation (WMI) provided by need.

private static UInt32 CountPhysicalProcessors()

{

     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 UInt64 CountPhysicalMemory()

{

   ManagementObjectSearcher objects =new ManagementObjectSearcher(

      “SELECT * FROM Win32_PhysicalMemory”);

   ManagementObjectCollection coll = objects.Get();

   UInt64 total = 0;

   foreach (ManagementObject obj in coll)

   {

       total += (UInt64)obj[“Capacity”];

    }

    return total;

}

 

Please add a reference to System.Management assembly, ensure that the code compiles correctly.

Console.WriteLine(“Machine: {0}”, Environment.MachineName);

Console.WriteLine(“# of processors (logical): {0}”, Environment.ProcessorCount);

Console.WriteLine(“# of processors (physical): {0}”  CountPhysicalProcessors());

Console.WriteLine(“RAM installed: {0:N0} bytes”,  CountPhysicalMemory());

Console.WriteLine(“Is OS 64-bit? {0}”,   Environment.Is64BitOperatingSystem);

Console.WriteLine(“Is process 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.WriteLine(“\tBitsPerPixel: {0}”,screen.BitsPerPixel);

}

 

 

 

3 read the registry key value pairs

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));

    }

}

 

Please add a namespace Microsoft.Win32, to ensure that the above code can be compiled.

 

4 start, stop Windows Service

The API provides utility functions are often used to manage application service without having to operate the control panel management service.

Controller = the ServiceController new new the ServiceController ( "EM- the POWER");       

controller.Start ();       

IF (controller.CanPauseAndContinue)       

{       

    controller.Pause ();       

    controller.Continue ();       

}       

controller.Stop ();       

// .NET provide the API may be implemented word installation and uninstallation service 

 IF (args [ 0 ] == " / I " ) 

 { 

       ManagedInstallerClass.InstallHelper ( new new  String [] {Assembly.GetExecutingAssembly ()} the Location.); 

 } 

 the else  IF (args [ 0 ] =="/u")

 {

   ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });

 }

 

 

As shown in the code, the application to pass parameters i or u, or to indicate that the installer is unloaded.

 

5 verify the program has strong name (P / Invoke)

For example in the program, in order to verify whether the assembly has a signature, the following method can be called

[DllImport("mscoree.dll", CharSet=CharSet.Unicode)]

static extern bool StrongNameSignatureVerificationEx(string wszFilePath, bool fForceVerification, ref bool  pfWasVerified);

 

bool notForced = false;

bool verified = StrongNameSignatureVerificationEx(assembly, false, ref notForced);

Console.WriteLine("Verified: {0}\nForced: {1}", verified, !notForced);

 

This feature is commonly used in software protection methods can be used to verify the signature components. Even if your signature is removed, or who all signed assemblies are removed, as long as this one calling code program, you can stop the program run.

 

6 Change Response system configuration items

For example, our after locking system, QQ if there is no exit, it displays a busy state.

Please add a namespace Microsoft.Win32, then registered the following events.

. DisplaySettingsChanged (comprising Changing) display settings 
. InstalledFontsChanged font changes 
. PaletteChanged  
. PowerModeChanged power state 
. SessionEnded (or end of the session the user is logged out) 
. SessionSwitch (change the current user) 
. TimeChanged time change 
. UserPreferenceChanged (user preferences comprising Changing number)

Our ERP system, will monitor the system time is changed, outside the scope of the ERP license file if the time is changed, it will lead to ERP software is not available.

 

7 use Windows7 new features

Windows7 system introduces a number of new features, such as Open File dialog box, the status bar shows the progress of the current task.

Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog ofd = new  Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog();

ofd.AddToMostRecentlyUsedList = true;

ofd.IsFolderPicker = true;

ofd.AllowNonFileSystemItems = true;

ofd.ShowDialog();

Open dialog In this way, the OpenFileDialog class library functions and BCL comes some more. But is limited to Windows 7 system, so to call this code, but also check the version of the operating system is greater than 6, and add a reference to the assembly Windows API Code Pack for Microsoft®.NET Framework, please go to this address to download  http : //code.msdn.microsoft.com/WindowsAPICodePack

 

8 inspection program memory consumption

By the following method, to check the amount of memory allocated to the program .NET

long available = GC.GetTotalMemory(false);

Console.WriteLine(“Before allocations: {0:N0}”, available);

int allocSize = 40000000;

byte[] bigArray = new byte[allocSize];

available = GC.GetTotalMemory(false);

Console.WriteLine(“After allocations: {0:N0}”, available);


In my system, the results of which runs as follows

Before allocations: 651,064

After allocations: 40,690,080

 

Use the following method, you can check the current application's memory usage

Process proc = Process.GetCurrentProcess();

Console.WriteLine(“Process Info: “+Environment.NewLine+

 “Private Memory Size: {0:N0}”+Environment.NewLine +

“Virtual Memory Size: {1:N0}” + Environment.NewLine +

“Working Set Size: {2:N0}” + Environment.NewLine +

“Paged Memory Size: {3:N0}” + Environment.NewLine +

“Paged System Memory Size: {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 a stopwatch to check the program run time

If you concerns certain code is time consuming, it can be used to check the time code StopWatch consumed, as shown in the following code

System.Diagnostics.Stopwatch timer = 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(“Sum of sqrts: {0}”,total);

Console.WriteLine(“Elapsed milliseconds: {0}”,

timer.ElapsedMilliseconds);

Console.WriteLine(“Elapsed time: {0}”, timer.Elapsed);

 

 

There are already specialized tools to detect the running time of the program, it can be refined to each method, such as dotNetPerformance software.

With the above code as an example, you need to directly modify the source code, if it is used to test the program, some inconvenience. Refer to the following examples.

class AutoStopwatch : System.Diagnostics.Stopwatch, IDisposable

{

   public AutoStopwatch()

   { 

       Start();

   }

   public void Dispose()

   {

       Stop();

       Console.WriteLine(“Elapsed: {0}”, this.Elapsed);

   }

}

 

By means of using the syntax, as shown in the following code can check the time a piece of code, and printed 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 using the cursor

When the program is running in the background or the save operation in addition to books, the cursor should be modified as busy state. 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 new ArgumentNullException(“control”);

   }

   _target = control;

   _prevCursor = _target.Cursor;

   _target.Cursor = Cursors.WaitCursor;

}

public void Dispose()

{

   _target.Cursor = _prevCursor;

}

}

Usage may throw exceptions shown below, this wording is to be expected to program

using (new AutoWaitCursor(this))

{

...

throw new Exception();

}

As shown in the code, even if an exception is thrown, the cursor can be restored to the state between.

Reproduced in: https: //www.cnblogs.com/majinyu/p/3192664.html

Guess you like

Origin blog.csdn.net/weixin_33830216/article/details/93665997