7. Code Access Security 7.1 What is Code Access Security (CAS)? CAS is part of the .NET security model, which determines if a code is allowed to be run, and what resources can be used when it runs. For example, CAS can prevent a .NET's web applet to format your hard drive. 7.2 How does Cas work? CAS Security Policy Design Two Key Concepts - Code Groups and Permissions. Each .NET component is a member of a particular code group, and each code group is granted by the permissions specified by the listing set. For example, when using the default security policy, a control downloaded from the Web site belongs to the "Zone - Internet" code group that keeps the permissions defined by the "Internet" by the Amissive Right Set Set. (Nature, the name "Internet" indicates a group of privileges that are strictly limited.) 7.3 Who defines the CAS code group? Microsoft defines some default code groups, but you can change these even created your own code group. To see the code group defined in your system, you can run the "Caspol -l" command from the command. I look like these in my system: level = Machine
Code Groups:
1. All code: Nothing 1.1 Zone - MyComputer:.. FullTrust 1.1.1 Honor SkipVerification requests: SkipVerification 1.2 Zone - Intranet:. LocalIntranet 1.3 Zone - Internet:. Internet 1.4 Zone - Untrusted:.. Nothing 1.5 Zone - Trusted: Internet 1.6 StrongName - 0024000004800000940000000602000000240000525341310004000003000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FEF8348EBD06F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8F83B465E0807AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D38561AABF5CAC1DF1734633C602F8F2D5:. Everything note code group hierarchy - top ( 'All code') is the most common, which is subsequently divided into several groups, each of which can also be subdivided. At the same time, the subgroups can be given a wider permission set than its superiors. 7.4 How to define your own code group? Use Caspol. For example, assume you trust the code from www.mydomain.com, and hope that it has full access to your system, but you want to maintain the default restrictions on other Internet sites. To achieve this, you can add a subgroup in the "Zone - Internet" group, just like the following: caspol -ag 1.3 -site www.mydomain.com FullTrust now if you run caspol -lg to see new code The group was added to 1.3.1 Group: ... 1.3. Zone - Internet: Internet 1.3.1. Site - www.mydomain.com: FullTrust ... Note Number Number (1.3.1) is just Caspol to be eaten so The command line is convenient to manipulate the code group. The bottom of the running library will never see it. 7.5 How to change the authority set of code group? Use Caspol. If you are a machine administrator, you can operate at 'Machine' Hierarchy - Not only means that you do will become the default setting of the machine, but the user cannot reform more widely. If you are an ordinary user (not an administrator) you can still modify the permissions, but you can only make them strict. For example, in order to make the intranet code to do what they want, you may need this: Caspol -cg 1.2 FullTrust pay attention, because (in a standard system), this is larger than the default security policy permissions, you should be on the Machine level. Do these - do not work in this User level. 7.6 Can I create my own permissions? Yes. Use caspol -ap to specify an XML file that contains all permissions in the permissions set. Here is an example file specified by 'everything' permission set - modify it to adapt to your needs, so you can save some time.
After the modification is complete, use the following method to add it to the available permissions: Caspol -ap samplepermset.xml then apply this permission set to a code group: casspol -cg 1.3 Samplepermset (By default, 1.3 is How to diagnose your own programs when there is a problem with the 'Internet' code group? Caspol has a group of possible options. First, use Caspol -RSG, you can let Caspol tell you which code group belongs to. Similarly, using Caspol -RSP, you can ask what permissions applied on a particular component. 7.8 I can't stand the trouble brought by CAS, can I turn off it? Yes, as long as you are a system administrator. Just run: Caspol -s Off 8. Intermediate Language (IL) 8.1 Can I see the middle language of the component? Yes. Microsoft provides a tool called ILDASM that can be used to view metadata and IL of the components. 8.2 Can I get the source code from IL by reverse engineering? Yes. Relatively, from IL to regenerate advanced language source code (e.g., C #) is usually very simple. 8.3 How to prevent someone from get my code through the reverse engineering? The only way to run is an ILASM with / owner option. The IL of the component generated can not be viewed through ILDASM. However, the deterministic code of the unconventional code can crack the ILDASM or write its own ILDASM version, so this method can only scare the burst of amateurns. Unfortunate things, current .NET compilers do not / owner options, so you need to protect your C # or VB.NET components, you need to do it below: CSC helloWorld.csildasm /out=temp.il HelloWorld.exeilasm / Owner Temp.il (This suggestion is Hany Ramadan to the DOTNET.) It seems to have an IL encryption tool over time (regardless of Microsoft or third parties). These tools will "optimize" IL in such a way that the reverse project has become more difficult. Of course, if you are writing a web service, the reverse project is no longer a problem, because the customer cannot access your IL. 8.4 Can I use IL to program directly? Yes. Peter Drayton posted this simple example in the DOTNET mailing list: .assembly myassembly {} .class myApp {.method static void main () {.entrypoint ldstr "Hello, IL!" Call void system.console :: WriteLine Class System.Object) RET}} Place it in a file called Hello.il, then runs ILASM Hello.il, an EXE component will be generated. 8.5 IL can do something you can't do in C #? Yes. Some simple examples are: You can throw an exception exported from systemException, and you can use an array of non-zero start. 9. Did it done about COM9.1 COM? Just as you can see in the mailing list, this topic leads to a fierce debate.
Take a look at the following two places: http://discuss.develop.com/archives/wa.exe?a2=ind0007&l=dotNet&d=0&p=68241 http://discuss.develop.com/archives/wa.exe?a2= IND0007 & L = DOTNET & P = R60761 My understanding is: COM contains a lot of content, and it is different for different people. But for me, COM is basically about how a small code is found to find another small code, and how to communicate with each other after they find each other. COM accurately indicates how this positioning and communication is going. In the "pure" .NET world consisting entirely of .NET objects, the small code is still looking for each other and talks with each other, but they don't use COM. They use a model that is very similar in certain places and COM - for example, type information saved in and component encapsulated together, which is very similar to the package in COM components. But it is not COM. So, is there any problem? Ok, I don't care about most COM disappeared - I don't care about the component is no longer related to the registry, I don't use IDL to define my excuse. But there is something I don't want it to disappear - I don't want to lose this idea based on the interface-based development. According to my opinion, COM's most powerful power is it insisted on erecting iron wall between interfaces and implementations. Unfortunately, it seems that .NET is no longer in that - it allows you to do an interface-based development, but it doesn't stick to it. Some people may argue that there is always a bad thing, maybe they are right, but I can't think that this may be a retreat. Did the DCOM died? Almost, especially for .NET developers. The .NET frame has a new remote model that is not DCOM. Of course, DCOM will also be used in interoperability. 9.3 MTS / COM done? Do not. The first .NET version considers the provision of existing COM services (via an interoperability layer) instead of using .NET's own services to replace them. Many tools and properties are used to achieve as smooth transition as possible. The PDC version of .NET SDK includes support for core services (JIT activities, transactions), but excludes some high-level services (such as COM events, queue components). In a period of time, interoperability can be expected to be seamless integration - this means that some services will become part of the CLR, and / or means that some services will be override and run in CLR in the form of manageable code. Top floor. For this topic, see Joe Long's Post-Joe is the manager of Microsoft's COM group. From here: http://discuss.develop.com/archives/wa.exe?a2=ind0007&l=dotNet&p=r68370 9.4 Can you use COM components in .NET? can. You can access the COM components from the .NET via the Runtime Callable Wrapper (RCW). It allows the COM interface to be accessed by mapping COM components to interfaces with .NET compatible interfaces. For the OldAutomation interface, you can automatically generate from a type library. For non-OleAutomation interfaces, a custom RCW can be developed to manually map the type of COM interface to the type with .NET compatible. For readers who are familiar with ATL, there is a simple example.
First, create an ATL component to implement the following IDL: import "oaidl.idl"; import "ocidl.idl"; [Object, UUID (EA013F93-487A-4403-86EC-FD9FEE5E6206), Helpstring ("icpname interface", Pointer_Default (unique), oleautomation] interface ICppName: IUnknown {[helpstring ( "method SetName")] HRESULT SetName ([in] BSTR name); [helpstring ( "method GetName")] HRESULT GetName ([out, retval] BSTR * pName };
[Uuid (F5E4C61D-D93A-4295-A4B4-2453D4A4484D), version (1.0), helpstring ( "cppcomserver 1.0 Type Library")] library CPPCOMSERVERLib {importlib ( "stdole32.tlb"); importlib ( "stdole2.tlb"); [UUID (600CE6D9-5ED7-4B4D-BB49-E8D5D5096F70), Helpstring ("CPPName Class")] CoClass cppname {[default] interface icpname;};}; after the component is established, you will get a TypeLibrary. Run the TLbimp utility on TypeLibrary, like this: TLBIMP CPPCOMSERVER.TLB If you succeed, you will get information like this: Typelib Imported successful to cppcomserverlib.dll Now you need a .NET client - we create one with C # Create a following Code .cs file: using system; using cppcomserverlib;
Public class mainapp {static public void main () {cppname cppname = new cppname (); cppname.setname ("bob"); console.writeline ("name is" cppname.getname ());}} Note We use Typelibrary The name as a namespace, the name of the COM class as class name. We can also choose to use cppcomserverlib.cppname as class names and do not need statements for CPPCOMSERVERLIB. Like this compiled above C # code: CSC /R: CppcomServerLib.dll Csharpcomclient.cs Note that compiling is notified, quote We just used Tlbimp from Typelibrary DLL. Now you should run csharpcomclient.exe, and get the following output from the console: Name is Bob 9.5 can use the .NET component in COM? can. The .NET component can be accessed from the COM via a COM CALLABLE WRAPER (CCW). This is similar to RCW (see the previous issue), but work in the opposite direction. Similarly, if it cannot be automatically generated by .NET development tool, or do not want to automatically generate behavior logic, you can develop a custom CCW. To enable COM to "see" .NET components, .NET components must be registered in the registry. Here is a simple example. Create a C # file called TestComServer.cs and enter the following code: use system;
namespace AndyMc {public class CSharpCOMServer {public CSharpCOMServer () {} public void SetName (string name) {m_name = name;} public string GetName () {return m_name;} private string m_name;}} then compiled .cs file: csc / Target: library testcomServer.cs You will get a DLL that registers it: regaSM testcomserver.dll /tlb:testcomServer.tlb Now you need to create a client program to test your .NET COM component. VBScript can - put the following in a file called Comclient.vbs: DIM DotNetobj Set DotNetobj = CreateObject ("Andymc.csharPcomserver") DotNetobj.setName ("Bob") msgbox "name is" & dotNetobj.getname () Run this script: wscript comClient.vbs 嘿! You get a message box that displays text "name is bob". (Note, when writing this program, it seems to be accessed by several paths as COM component - To avoid problems, run Comclient.vbs in the same directory in TestComServer.dll. One alternative method is to use Jason Whittington DM.NET MONIKER developed with Don Box. Http://staff.develop.com/jasonw/clr/readme.htm View. 9.6 Is ATL in the .NET? Yes. If you are Write an application within the .NET framework. Of course, many developers want to continue using the ATL to write C COM components other than the .NET framework, but when you are in the .NET framework, you always want to use C # in .NET World The original C (and its ATL) did not have too many status - it's too direct and provided too much adaptability, so that the running library could not manage it. 10. Miscellaneous 10.1 .NET remote calculation Remote calculations for work? Net involve sending messages through channels. The two standard channels are HTTP and TCP. Only in the LANs tend to use TCP-HTTP can be used on the local area network and wide area network (INTERNET). Now Support, such as SOAP (Based on XML) and binary formats. By default, HTTP channel uses SOAP (Serialization SOAP FORMATTER through .NET Runture), while TCP channels use binary format (run through .NET) The library's Serialization Binary Formatter. But each channel can be used in any serialization format. Here is some ways to access: SINGLECALL. Each request from the client is a new object service. When the request is completed, the object is discarded. You can use ASP national services in the ASP environment to save applications or sessions, so that this model (no country is divided) has become a country support. Singleton. All requests on the client are single server objects Handling. Client-activated object.
This is the old country support (D) COM model, where the client is received by a remote object and retains this reference (to maintain the remote object's survival) until it is completed. The distributed garbage collection of objects is managed by the "Based on Rent Lifecycle". Each object has a rental time, which is disconnected from the .NET running library when arriving at this time. Objects have default update time - the successful call initiated from the client will update the rental time. The client can also update the rental time. If you use XML-RPC instead of SOAP, you can see Charles Cook at http://www.cookcomputing.com/xmlrpc/xmlrpc.shtml XML-RPC.NET site. 10.2 How to get Win32 API in .NET? Use P / Invoke. It uses technologies similar to COM interoperability, but is used to access static DLL entry points instead of COM objects. The following is a C # program calls the Win32 MessageBox function example: using System; using System.Runtime.InteropServices; class MainApp {[dllimport ( "user32.dll", EntryPoint = "MessageBox", SetLastError = true, CharSet = CharSet.Auto) ] Public Static Extern Int MessageBox (int hWnd, string strmessage, string strcaption, uIint uitype);
Public static void main () {MessageBox (0, "Hello, This Is Pinvoke In Operation!", ".NET", 0);}} 11. Class library 11.1 file I / O11.1.1 How to read text files? First, use the System.IO.FileStream object to open the file: filestream fs = new filestream (@ "c: /test.txt", filemode.open, fileaccess.read; filestream inherits in Stream, so you can use a streamreader object FileStream object packages. This provides a good interface for a row of rows: streamreader sr = new streamreader (fs); string curline; while ((curline = sr.readline ())! = Null) Console.Writeline (curline); Turn off the StreamReader object: sr.close (); Note This will automatically call close () on the underlying Stream object, so you do not have to display fs.close (). 11.1.2 How to write a text file? Similar to the example of reading the file, just replace StreamReader to streamwriter. 11.1.3 How to read a binary? Similar to text files, just use binaryreader / write objects instead of streamreader / write to pack the filestream object. 11.1.4 How to delete a file? Use static methods to use the static method (): file.delete (@ "c: /test.txt"); 11.2 text processing 11.2.1 Support regular expressions? Yes. Use the System.Text.RegularExpressions.Regex class. For example, the following code updates the title of the HTML file: FileStream Fs = New FileStream ("Test.htm", FileMode.Open, FileAccess.Read; StreamReader SR = New StreamReader (fs);
Regex r = new regex ("
HTTPWebRequest Request = (httpwebrequest) WebRequestFactory.create ("http: // localhost"); request.proxy = proxydata; 11.4 XML11.4.1 Supply DOM? Yes. Take a look at the following sample XML document:
XMLNode root = doc.documentelement;
"XMLNode PersonElement in root.childnodes) console.writeline (PersonElement.firstchild.value.tostring ()); output is: Fredbill 11.4.2 Supply SAX? Do not. As a replacement, a new XMLReader / XMLWRITER API is provided. Like SAX, it is streaming, but it uses the "PULL" model rather than the "Push" model of SAX. This is an example: XmlTextReader Reader = New XMLTextReader ("test.xml"); while (Reader.NodeType == XMLNodetype.Element && Reader.Name == "Person") {Reader. Read (); // skip to the child text console.writeline (});}} 11.4.3 Does XPath? Yes, through the XMlnavigator class (Documentnavigator is exported from XMLnavigator): XmLDocument Doc = New XmLDocument (); Doc.Load ("Test.xml");
Documentnavigator nav = new documentnavigator (doc); nav.movetodocument ();
Nav.Select ("Descendant :: People / Person);
While (nav.movetonextSelected ()) {nav.movetofirstchild (); console.writeline ("{0}", nav.value);} 11.5 Thread 11.5.1 Supply multi-threaded? Yes, there is a wide range of support for multithreading. The system can generate a new thread and provide a thread pool that the application can use. 11.5.2 How to generate a thread? Create an instance of the System.Threading.Thread object to pass the ThreadStart sample that will be executed in the new thread to it. For example: class mythread {public mythread (String initdata) {m_data = initdata; m_thread = new thread (new threadstart (threadmain)); m_thread.start ();}
// threadmain () is executed on the new thread. Private void threadmain () {console.writeline (m_data);
Public void waituntilfinished () {m_thread.join ();
Private thread m_thread; private string m_data;} One instance of creating Mythread is enough to generate threads and execute mythread.threadmain (): mythread t = new mythread ("Hello, World."); t.waituntilfinished (); 11.5. 3 How to stop a thread? There are several ways. First, you can use your own communication mechanism to tell the threadstart method to end. In addition, the Thread class has built-in support to command the thread to stop. Basic two methods are Thread.Interrupt () and thread.abort (). The former caused a ThreadInterruptedException and then entered the WaitJointEP state. In other words, Thread.Interrupt is a polite way that requests the thread to stop when there is no useful work. Corresponding to this, thread.abort () throws a ThreadAbortexception instead of the consignment of the thread. Moreover, ThreadAbortException cannot be captured as usual (even if the THReadStart termination) is performed. Thread.abort () is a very means of unnecessary under normal circumstances. 11.5.4 How to use a thread pool? One example of the transfer by the ThreadPool.QueueUserWorkItem WaitCallback () method: class CApp {static void Main () {string s = "Hello, World"; ThreadPool.QueueUserWorkItem (new WaitCallback (DoWork), s); Thread.Sleep (1000 ); // give time for work item to be executed}
// DOWORK IS EXECUTED ON A Thread from the thread pool. Static void DOWORK (Object State);}} 11.5.5 How do I know when my thread pool work project is completed? There is no way to ask the thread pool such information. You must place the code in the waitCallback method to issue a signal to indicate that it has been completed. The event here is also useful. 11.5.6 How to prevent concurrent access to the data? Each object has a unlocked and unlocked part of the criticism. System.Threading.monitor.Enter / Exit method is used to get and release the lock. For example, the following examples only allow one thread to simultaneously enter the method f (): Class C {public void f () {Try {Monitor.Enter (this); ...} Finally {Monitor.exit (this);}} } C # has a keyword 'lock' provides simple form of the above code: Class C {public void f () {loc (this) {...}}} Note, calling Monitor.Enter (MyObject) does not mean All access to myObject is serially connected. It means the synchronization lock that is associated with myObject and no other thread can request the lock before calling Monitor.exit (o). In other words, the following class and the class given above are functionally equivalent: Class C {public void f () {lock (m_object) {...}}
Private m_object = new object (); 11.6 Tracking 11.6.1 Is there a built-in tracking / log support? Yes, in the system.diagnostics namespace. There are two main classes for processing tracks - Debug and Trace. They work in a similar manner-different is that the tracking in the Debug class can only work in the code generated by the Debug flag, and the tracking in the Trace class can only work in the code generated by the Trace tag. Typically, this means you should use System.Diagnostics.Trace.writeline when you want to track in debug and release versions, and use system.diagnostics.debug when you want to track it in the debug version. .Writeline. 11.6.2 Can I redirect the tracking output to a file? Yes. Both the Debug class and the Trace class have a listners attribute, which collects the output you generated by Debug.Writeline or Trace.writeline. By default, only one collection slot is an instance of the DEFAULTTRACELISTENER class. It sends output to Win32 OutputDebugString () function and system.diagnostics.debugger.log () method. This is useful when debugging, but if you try to track a problem from the customer site, it is more appropriate to redirect the output to a file. Fortunately, the TEXTWRITERTRACELISTENER class is provided for this purpose. Here is how TextWritertracelistener redirects the Trace output to a file: trace.listener (); filestream fs = new filestream (@ "c: /log.txt", filemode.create, fileaccess.write; trace.listener. Add (FS)); Trace.Writeline (@ "this will be writen to c: /log.txt!"); Note Use trace.listener.clear () remove the default Listener. If not do it, the output will be generated simultaneously in the file and OutputDebugString (). Under normal circumstances, you don't want this, because OutputDebugString () leads to great performance overhead. 11.6.3 Can you customize the output of tracking? Yes. You can write your own tracelistener export class and redirect all output to it. Here is a simple example, it exports from the TextWritrtracelistener (and then built on the write files) and add time information and thread ID: Class MyListener: TextWritRaceListener {public MyListener (Stream S): BASE (s) {}
Public override void writeline ("{0: D8} [{1: D4}] {2}", Environment.TickCount - m_starttickcount, appdomain.getCurrentThreadId (), s);}