The code snippets that are frequently used in. NET development are completely extracted from the actual project, and can be repeatedly borrowed by multiple users.

Source: Internet
Author: User

A few years ago, an article titled 33 types that ASP. NET developers often useCodeIs very popular, it summarizes some frequently used code in ASP. NET development, can be used directly. Repeat this article todayArticleThanks to my comments, being good at summing up is also progress, so I also summarized some common code snippets from my projects and shared them with you.

Write a text file
 
Textwriter Tw =NewStreamwriter ("Date.txt"); TW. writeline (datetime. Now); TW. Close ();

Read text files

 
Method 1
Textreader TR =NewStreamreader ("Date.txt"); Console. writeline (tr. Readline (); tr. Close (); method 2
Streamreader reader =NewStreamreader ("Date.txt"); Console. writeline (reader. Readline (); reader. Close ();
 
 

In fact, there is a bug in writing and reading text files.ProgramWhen the code is changed to the front directory, the Directory of date.txt is the directory to be changed, not all the directories of the current application we expect. Therefore, the recommended method is as follows:

 
StringFile ="Cnblogs.txt";StringCnblogs = path. Combine (system. appdomain. currentdomain. basedirectory, file );If(File. exists (cnblogs )){Using(Streamreader reader = file. opentext (cnblogs) {rtfcnblogs. Text = reader. readtoend ();}}

Added the complete file name path, which is the correct method for reading and writing files. For ASP. NET applications, you can use server. mappath instead,

Or httpcontext. Current. Request. physicalapplicationpath.

 

Cross-thread access control
Delegate VoidDsettext (string text );Private VoidSettext (string text ){
 
If(Invokerequired)
 
{
 
Dsettext d =NewDsettext (settext );
 
This. Invoke (d );
 
}
Else{
 
This. Textbox1.text = text;
 
}}
 
 
Call the code Smith Template
 
Codetemplatecompiler compiler =NewCodetemplatecompiler (@ "C: \ test. CST"); Compiler. Compile ();If(Compiler. errors. Count = 0) {codetemplate T = compiler. createinstance ();This. Txtsql. Text = T. rendertostring ();} compiler. Cleanup (); compiler =Null;

For x64 systems, set target to x86 (need to set the program to compile as x86 ).

 

Set the runtime version of the Assembly

When the old program is. and cannot be upgraded to. NET 2.0. net 4.0, while some components are. net compilation. during runtime, the exception of the hybrid assembly will be thrown. You need to modify the configuration file. Please refer to this section.

 
   "1.0" ?> 
   
   
     "true"  
    
      "true" 
      imageversion = 
      "v4.0.30319"  Version = 
      "v4.0.30319" /> 
      
    
   
   

This requirement comes from the fact that code Smith 5.0 is compiled with. NET 2.0. In my code generator, it is used to reflect and read assembly information and generate code. The target of the read assembly is. net 4.0. In this case, you need this technique to solve the running problems.

Another scenario is ilmerge, which is used for merging. net Assembly Tool, only.. NET 2.0 version, which can be merged. net 4.0 Assembly, also need to use this technique (ilmerge config file for executing within the CLR v4.0 runtime ).

 

Enumeration type reflection call

In some scenarios, we need to pass the reflected parameter value to the object method, and the parameter value is of the enum type, which is not easy to implement.

Please refer to the article setting Enum's through reflection in codeproject. Its classic code is as follows:

 
IntEnumvalue1 = (Int) Enumitem1.getvalue (enumtype );IntEnumvalue2 = (Int) Enumitem2.getvalue (enumtype );IntCurrentvalue = (Int) Flagsinfo. getvalue (remoteobject,Null);IntNewvalue = currentvalue | enumvalue1 | enumvalue2;

For example, I need to reflect the object instance that generates the reportviewer control, and pass a mode value to it (server, localreport) to indicate whether it is a local report or a server report. In this case, the value must be passed in through reflection.

In my. Net general platform, I also applied this technology to create the crystalreportviewer report control in reflection mode, and then input the parameter value. This method is a little more complicated, but it is worth comparing the flexibility it brings.

 

Directory Selection
Folderbrowserdialog DLG =NewFolderbrowserdialog ();If(!String. Isnullorempty (txtpath. Text) DLG. selectedpath = txtpath. text;If(DLG. showdialog () = dialogresult. OK) {txtpath. Text = DLG. selectedpath ;}
 
 
File Selection
 
Openfiledialog DLG =NewOpenfiledialog (); DLG. Filter ="All file (*. *) | *.*";If(DLG. showdialog () = dialogresult. OK) {txtpath. Text = DLG. filename ;}

Filter is an option that is often easy to forget.

DLG. Filter = "XML file (*. XML) | *. xml | all files | *.*";

 
 

Read the resource files embedded in the Assembly.
 Assembly assm = assembly. getassembly ( typeof  (databasecleanup ));  string  file =  "databasecleanup.txt" ; stream input = assm. getmanifestresourcestream ( "dataloader. resource " +  ". " + file); streamreader reader =  New  streamreader (input );  string  SQL = reader. readtoend (); reader. close (); 

If possible, use embedded resource as far as possible for Read-Only configuration option resources (SQL statements, text files) that do not need to be modified.

 

Call method of Microsoft enterprise database

After a simple encapsulation, the following method calls the enterprise database to access the database:

Enterpriselibraryshared. connectonstring = connectionstring; Microsoft. Practices. enterpriselibrary. Data. Database m_commondb = databasefactory. createdatabase (); dbcommand cmd = m_commondb.getsqlstringcommand (SQL );IntRowaffected = m_commondb.executenonquery (CMD );

I put the connection string of the Enterprise Library into a static class, which can simplify the call method, without the need to add the APP/Web. config file.

 

Changes in monitoring files or directories

This function is commonly used. There is also a PDF watcher program in Data Loader to monitor whether a newly added PDF file exists in the specified directory (possibly from remote transmission, or download it from the web page), convert it, and import it to the Document Server.

  Public   void  startmonitor ( string  path) {filesystemwatcher watcher =  New  filesystemwatcher (); watcher. path = path; watcher. policyfilter = policyfilters. filename;  // only watch PDF files.  watcher. filter =  "*. PDF "; watcher. created + =  New  filesystemeventhandler (onchanged); watcher. enableraisingevents =  true  ;}  // event handler for when a file is created in the watched folder   private   void  onchanged ( Object  source, filesystemeventargs e) { string  word = documentutility. convert‑todoc (E. fullpath) ;}

 

Hope to help you.

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.