C # programming practices

Source: Internet
Author: User
Tags visual studio 2002

Author: Chen Province

Recently, I learned how to use C # programming, because I used Delphi and found that C # class libraries are still not perfect (I used. net Framework 1.0. I don't know.. Net Framework 1.1). In addition, Visual Studio 2002 is not perfect. I don't know what improvements Visual Studio 2003 has. For example, you cannot specify the Default Input Method (Correction: To control the input method, the. NET class library is supported in the System. Windows. Forms. InputLanguage class). Therefore, I have to write an Ini plugin class and a class for switching the input method based on the input method name.

Problem list:

C # Ini plugin class
C # Input Method Switching
Use C # To read and write files
Format a string
Load custom resources from Assemble
Sort StringCollection
C # Builder Open Tools Api Bug
Use reflection to dynamically set component Properties
Copy string to clipboard
Obtain the version information of a program file.
Dynamic Loading of Assembly Using Reflection
Other problems

C # ini plugin class

Using System;
Using System. IO;
Using System. Runtime. InteropServices;
Using System. Text;
Using System. Collections;
Using System. Collections. Specialized;
Using system. Windows. forms;

Namespace sharpplus. ini {
/// <Summary>
/// A Tinifile class that imitates Delphi
/// Revision: 1.1 corrected the support for the Chinese system.
/// 1.2 added the updatefile method to support Win9x
/// 1.3 added the read and write operations of Boolean and integer values.
/// 1.4 corrected the failure of writing INI, but an exception error is thrown.
/// 1.5 readstring returns the string after trim
/// 1.6 unify and expand the size of the read/write buffer
/// </Summary>
Public class INIFILE {
Public String filename; // INI File Name
// Declare the API function for reading and writing INI files
[Dllimport ("Kernel32")]
Private Static extern bool writeprivateprofilestring (string section, string key, string Val, string filepath );
[Dllimport ("Kernel32")]
Private Static extern int getprivateprofilestring (string section, string key, string def, byte [] retval, int size, string filepath );
// Class constructor, passing the INI File Name
Public IniFile (string AFileName ){
// Determine whether a file exists
FileInfo fileInfo = new FileInfo (AFileName );
// Todo: Find out the usage of enumeration
If ((! FileInfo. Exists) // | (FileAttributes. Directory in fileInfo. Attributes ))
Throw (new ApplicationException ("INI file does not exist "));
// It must be a full path, not a relative path
FileName = fileInfo. FullName;
}
// Write the INI File
Public void WriteString (string Section, string Ident, string Value ){
If (! WritePrivateProfileString (Section, Ident, Value, FileName ))
{
// Todo: throw a custom exception.
Throw (new ApplicationException ("An error occurred while writing the INI file "));
}
}
// Read the specified INI File
Public string ReadString (string Section, string Ident, string Default ){
// StringBuilder Buffer = new StringBuilder (255 );
Byte [] Buffer = new Byte [65535];
Int bufLen = GetPrivateProfileString (Section, Ident, Default, Buffer, Buffer. GetUpperBound (0), FileName );
// The encoding method of 0 (the default code page of the system) must be set. Otherwise, Chinese characters cannot be supported.
String s = Encoding. GetEncoding (0). GetString (Buffer );
S = s. Substring (0, bufLen );
Return s. Trim ();
}

// Read integer
Public int ReadInteger (string Section, string Ident, int Default ){
String intStr = ReadString (Section, Ident, Convert. ToString (Default ));
Try {
Return Convert. ToInt32 (intStr );
}
Catch (Exception ex ){
Console. WriteLine (ex. Message );
Return Default;
}
}

// Write an integer
Public void WriteInteger (string Section, string Ident, int Value ){
WriteString (Section, Ident, Value. ToString ());
}

// Read Boolean
Public bool ReadBool (string Section, string Ident, bool Default ){
Try
{
Return Convert. ToBoolean (ReadString (Section, Ident, Convert. ToString (Default )));
}
Catch (Exception ex ){
Console. WriteLine (ex. Message );
Return Default;
}
}

// Write Bool
Public void WriteBool (string Section, string Ident, bool Value ){
WriteString (Section, Ident, Convert. ToString (Value ));
}

// From the INI file, add all Ident in the specified Section name to the list
Public void ReadSection (string Section, StringCollection Idents ){
Byte [] Buffer = new Byte [16384];
// Idents. Clear ();

Int bufLen = GetPrivateProfileString (Section, null, null, Buffer, Buffer. GetUpperBound (0 ),
FileName );
// Parse the Section
GetStringsFromBuffer (Buffer, bufLen, Idents );
}

Private void GetStringsFromBuffer (Byte [] Buffer, int bufLen, StringCollection Strings ){
Strings. Clear ();
If (bufLen! = 0 ){
Int start = 0;
For (int I = 0; I <bufLen; I ++ ){
If (Buffer [I] = 0) & (I-start)> 0 )){
String s = Encoding. GetEncoding (0). GetString (Buffer, start, I-start );
Strings. Add (s );
Start = I + 1;
}
}
}
}
// Read the names of all the Sections s from the INI File
Public void ReadSections (StringCollection SectionList ){
// Note: Bytes must be used for implementation. StringBuilder can only obtain the first Section.
Byte [] Buffer = new byte [65535];
Int bufLen = 0;
BufLen = GetPrivateProfileString (null, Buffer,
Buffer. getupperbound (0), filename );
Getstringsfrombuffer (buffer, buflen, sectionlist );
}
// Read all values of the specified section to the list
Public void readsectionvalues (string section, namevaluecollection values ){
Stringcollection keylist = new stringcollection ();
Readsection (section, keylist );
Values. Clear ();
Foreach (string key in keylist ){
Values. Add (Key, readstring (section, key ,""));
}
}
// Clear a Section
Public void erasesection (string section ){
//
If (! Writeprivateprofilestring (section, null, null, filename )){
Throw (New applicationexception ("section in the INI file cannot be cleared "));
}
}
// Delete the key under a section
Public void deletekey (string section, string ident ){
WritePrivateProfileString (Section, Ident, null, FileName );
}
// Note: For Win9X, You need to implement the UpdateFile method to write data in the buffer to the file.
// On Win NT, 2000, and XP, files are directly written without buffering. Therefore, you do not need to implement UpdateFile.
// After modifying the INI file, call this method to update the buffer zone.
Public void UpdateFile (){
WritePrivateProfileString (null, FileName );
}

// Check whether a key value in a Section exists
Public bool ValueExists (string Section, string Ident ){
//
StringCollection Idents = new StringCollection ();
ReadSection (Section, Idents );
Return Idents. IndexOf (Ident)>-1;
}

// Ensure resource release
~ IniFile (){
UpdateFile ();
}
}
}

C # Input Method Switching

The C # editing component only has the ImeMode attribute and does not have the ImeName attribute of the component in Delphi. The following class can be used to set the Ime of the current system based on the ImeName. (Correction: To control the input method, the. NET class library is supported in the System. Windows. Forms. InputLanguage class .)

Using System;
Using System. Runtime. InteropServices;
Using System. Collections;
Using Microsoft. Win32;

Namespace Screen
{
/// <Summary>
/// Summary of Ime.
/// Implement the local input method
/// Refer to the implementation in Delphi
/// </Summary>
Public class Ime
{

[DllImport ("user32")]
Private static extern uint ActivateKeyboardLayout (uint hkl, uint Flags );
[DllImport ("user32")]
Private static extern uint LoadKeyboardLayout (string pwszKLID, uint Flags );
[DllImport ("user32")]
Private static extern uint GetKeyboardLayoutList (int nBuff, uint [] List );

Private static Hashtable FImes;
Public static uint kll_activate = 1;

Public Ime ()
{
//
// TODO: add the constructor logic here
//
}

// Set the current Ime. Use Ime. SetImeName ("Chinese (simplified)-pinyin plus ");
Public static void SetImeName (string ImeName)
{
// String format
If (FImes = null)
GetImes ();
Uint id = Convert. ToUInt32 (FImes [ImeName]);
SetIme (id );
}

Public static void SetIme (uint ImeId)
{
// Id Style
If (ImeId> 0)
ActivateKeyboardLayout (ImeId, kll_activate );
}

// Obtain all Ime lists
Public static Hashtable GetImes ()
{
If (FImes = null)
FImes = new Hashtable ();
Else
Return FImes;
Uint [] KbList = new uint [64];
Uint totalkblyout = GetKeyboardLayoutList (64, KbList );

For (int I = 0; I <totalkblyout; I ++)
{
String RegKey = String. Format ("System \ CurrentControlSet \ Control \ Keyboard Layouts \ {0: X8}", KbList [I]);
RegistryKey rk = Registry. LocalMachine. OpenSubKey (RegKey );
If (rk = null)
Continue;
String ImeName = (string) rk. GetValue ("layout text ");
If (ImeName = null)
Continue;
FImes. Add (ImeName, KbList [I]);
}
Return FImes;
}
}
}

Other IDE and class library Problems

Problems with Visual Studio 2002 ide
The variables in the monitoring window cannot be deleted when the debugging point is not reached.
You cannot rename an event.
The title of the newly created window is sometimes lost.
After the program is started frequently, you cannot see the interface. You must stop debugging and run it again.
. NET Framework 1.0 Problems
The form does not have the activecontrol attribute, Which is unpleasant.
The title page of the tab in tabcontrol cannot be hidden, so it cannot be used to implement the expert wizard interface.
When the sorted attribute of Treeview is true, insert a node is automatically sorted. The custom sorting function is not provided.
The coordinates transmitted by the event are system coordinates rather than component coordinates. You need to call pointtoclient to convert them.
Oledbdatareader is a dedicated connection. If a datareader is not closed, other datasets cannot be used. While Delphi's dbexpress is also a one-way cursor, it does not affect the use of other data components when using one component.
Access is very poorly supported. Using like for Fuzzy queries may sometimes cause buffer overflow.

Use C # To read and write files

The following code illustrates how to write data from a dataset to a file.
Try
{
DbConn. Open ();
OleDbDataReader Reader = CommandLog. ExecuteReader ();
Try
{
Streamwriter Sw = new streamwriter (SaveFile, false,
Encoding. ASCII );

While (reader. Read ())
{

String S = reader ["ip"] + "--";
Datetime dt = (datetime) Reader ["visitdate"];
// Format the date string in the Date Format
Cultureinfo CI = new cultureinfo ("En-us ");

String visitdate = DT. tostring ("DD/Mmm/yyyy: hh: mm: SS", CI );

S = S + "[" + visitdate + "-0700]";
String ref = (string) Reader ["Referer"];
// If there is no refer
If (ref. Trim ()! = "")
{

S = S + "\" Get/HTTP/1.1 \ "200 23989 \" "+ ref +" \ "\" "+ reader [" useragent "] + "\"";
Sw. writeline (s );
}

}

Sw. Close ();
}
Finally
{
Reader. Close ();
}

}
Catch (Exception e)
{
Console. WriteLine ("exception \ n {0}", e. Message );
}
}

Format a string

String result = String. Format ("Select * from TblCategory where (ParentId = {0}) order by CategoryIndex", Pid );

C # builder open tools api bug

1. CodeDom cannot obtain the row number of the constructor.
2. Unable to obtain the Internal Protected member.
3. Files cannot be deleted from the project.
4. C # Builder IOTAModuleInfo. ModuleType returns all empty strings
5. The IOTASearchOptions interface is not supported.

Use reflection to dynamically set component Properties

You can use typeof (Component) to obtain the Type object and call GetProperties to obtain the attribute list.
The GetProperty method obtains the PropertyInfo object, and then calls the SetValue of the PropertyInfo object to set the value. Example:

System. Type btnType = button1.GetType ();
PropertyInfo [] props = btnType. GetProperties ();

Foreach (PropertyInfo prop in props ){
If (prop. Name = "Text ")
Prop. SetValue (button1, "test", null );
}

To notify the IDE component attributes of changes, add the following code example:

PropertyDescriptor backColorProp =
TypeDescriptor. GetProperties (Control) ["BackColor"];

If (backColorProp! = Null ){
BackColorProp. SetValue (Control, Color. Green );

You can also use IComponentChangeService to implement notifications.

Sort stringcollection

The StringCollection class corresponds to the TStringList class in Delphi. However, compared with the TStringList class, the sorting function is missing. Therefore, I have written a method to sort the StringCollection.

// Sort StringCollection
Public static void Sort (StringCollection Strs, bool CaseSensitive ){
IComparer comparer = null;
If (CaseSensitive)
Comparer = Comparer. DefaultInvariant;
Else
Comparer = CaseInsensitiveComparer. DefaultInvariant;
QuickSort (Strs, 0, Strs. Count-1, comparer );
}

Private static void QuickSort (StringCollection Strs, int L, int R, IComparer comparer ){
While (true ){
Int I = L;
Int J = R;
Int P = (L + R)/2;
While (true ){
While (comparer. Compare (Strs [I], Strs [P]) <0)
I ++;
While (comparer. Compare (Strs [J], Strs [P])> 0)
J --;
If (I <= J ){
ExchangeStrings (Strs, I, J );
If (P = I)
P = J;
Else if (P = J)
P = I;
I ++;
J --;
}
If (I> J)
Break;
}
If (L <J)
QuickSort (Strs, L, J, comparer );
L = I;
If (I> = R)
Break;
}
}

// Position of the exchanged string
Public static void ExchangeStrings (StringCollection Strs, int I, int J ){
String Si = STRs [I];
String SJ = STRs [J];
STRs. removeat (I );
STRs. insert (I, SJ );
STRs. removeat (j );
STRs. insert (J, Si );
}

Load custom resources from assemble

Use resourcer to add icons, bitmaps, strings, and other resources to the resx file, and then call the following sample code to load the resource:

// Load Resources
ResourceManager Rm =
New ResourceManager ("sharpplus. Resources", assembly. getexecutingassembly ());
Icon logoicon = (icon) Rm. GetObject ("logo. ICO ");

Copy string to clipboard

Clipboard. setdataobject ("test ");

Obtain the version information of a program file.

// Obtain the version of the runtime assembly
Public static string getassemblyversion ()
{
Assembly myassembly = assembly. getexecutingassembly ();
Fileversioninfo myfileversion = fileversioninfo. getversioninfo (myassembly. Location );
Return string. Format ("{0}. {1}. {2}", myFileVersion. FileMajorPart, myFileVersion. FileMinorPart, myFileVersion. FileBuildPart );
}

Dynamic Loading of Assembly Using Reflection

String dllName = "OverSeer. dll ";
Type t = ReflectionUtils. GetType (dllName, "uDbg. Unit ");
Dt = ReflectionUtils. GetType (dllName, "uDbg. TNxDebugger ");
// MethodInfo mi = t. GetMethod ("Debugger", BindingFlags. Static | BindingFlags. Public );
// Object debugger = mi. Invoke (null, null );
If (t = null)
Return;
// Dynamically execute the static Debugger Method
Debugger = t. InvokeMember ("Debugger", BindingFlags. Public | BindingFlags. Static | BindingFlags. InvokeMethod, null, null );

// Dynamically Retrieve the type metadata based on the Assembly name and type name
Public static Type GetType (string AssemblyName, string TypeName)
{
FileInfo info = new FileInfo (AssemblyName );
If (! Info. Exists)
Return NULL;
Assembly A = assembly. loadfrom (assemblyname );
// Todo: Exception Handling
Return A. GetType (typename );
}

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.