Showing posts with label .NET Framework. Show all posts
Showing posts with label .NET Framework. Show all posts

Monday, October 30, 2006

Directory V.S. DirectoryInfo

d Someone said: Directory is a static class, while DirectoryInfo can be instantiated. Basically, both work the same.

d The Directory class exposes static methods you can use to create, move, and delete directories. The DirectoryInfo represents a specific directory and lets you perform many of the same actions as the Directory class on the specific directory. Additionally, it enumerates child directoreis and files.

Copying files and directories in .NET

Tuesday, October 24, 2006

My Naming Conventions in .NET

^ 我想尽量兼顾VB.NET和C#。

^ Field/Class Variable: Pascal Case。Always indicate Private, do not use Dim.

^ Property: Pascal Case。

^ Parameter: Camel Case。在method body中,定义一个Local Variable,采用Pascal Case命名,除了首字母其他完全一致,然后把parameter赋值给相应的Local Variable。

^ Property和Method是给“外人”看的,命名要“好看”,所以就要规规矩矩地Pascal Case。Field是自己用的,所以命名可以有点儿“特色”。

d Field: Camel Case with Leading Underscore. In VB.NET, always indicate "Protected" or "Private", do not use "Dim".
Of all the items here, the leading underscore is really the only controversial one. I personally prefer it over straight underscore-less camel case for my private variables so that I don't have to qualify variable names with "this." to distinguish from parameters in constructors or elsewhere where I likely will have a naming collision. With VB.NET's case insensitivity, this is even more important as your accessor properties will usually have the same name as your private member variables except for the underscore.


d Properties: Pascal Case, no underscores. Try to avoid abbreviations. Members must differ by more than case to be usable from case-insensitive languages like Visual Basic .NET.
VB: Public Property RecordID As Integer
C#: public int RecordID

d Parameters: Camel Case. Try to avoid abbreviations. Parameters must differ by more than case to be usable from case-insensitive languages like Visual Basic .NET.
VB: ByRef recordID As Integer
C#: ref int recordID

d What are your thoughts on naming conventions that need to be used to distinguish the class variables, function local variables and method arguments?
d By class variables, I assume you mean fields. Those should be private (use properties for public exposure to provide a level of abstraction). For function locals, those are by definition private. For method arguments, those need to be camelCased. For the privates, I have seen two patterns in the .NET Framework: one is leading underscore, and the other is this.Foo. Either works for me.

d However, I then had to do some VB.NET development and the language isn't case sensitive. I've seen some examples that add a "Field" suffix in VB.NET . I think that is worse than a leading "_". So I came full circle and started using "_" again. :)

e Designing .NET Class Libraries: Naming Conventions (January 26, 2005)
e .NET Programming Standards and Naming Conventions

Sunday, October 22, 2006

Using unmanaged code

^ What is Interoperation for?
There might be many lines of legacy code left for companies. If they had to rewrite and retest thiese codes prior to launching any new application developed in .NET, they would have never made the switch. Using an "all or nothing" approach with migrating to .NET is simply too expensive and time consuming for many companies with investments in legacy code.
By taking advantage of Interoperation, they are able to migrate their existing applications little by little, in a manner that was virtually transparent to clients. Were it not for Interoperation, they would have never made the migration.


^ Prior to advent of the .NET Framework, the COM Framework was the primary framework for developers to interact with the Windows operating system.

d The mechanism that serves as proxy so that the .NET runtime can communicate with a COM component is known as a Runtime Callable Wrapper (RCW), which handles the majority of the work between .NET and COM for you, including marshaling data types, handling events, and handling interfaces.

d Unlike pure .NET components, COM components must be registered before they can be used.
d Every COM components must have an entry in the Windows registry.

d After importing it, using an object contained in a given COM library is virtually identical to using ne created purely in .NET.

d What is Platform Invoke? and when to use it?

d Use Platform Invoke through the System.Runtime.InteropServices namespace:


  1. Create a static/shared external method with the name of the function you want to call.
  2. Decorate it with the DllImport attribute specifying the library that it should call.
  3. Call the method from your code.

Imports System.Runtime.InteropServices
Public Class InterExample


Private Shared Function GetForeWindow() As IntPtr
End Function

Public Shared Sub GetScreenDemo()
Dim DemoHandle = GetForeWindow()
End Sub

End Class
d Encapsulating DLL Functions: Because Platform Invoke calls is not elegant, it's often beneficial to create a class that exposes them and wraps this functionality. After all, much of the .NET Framework is composed of precisely this methodology.
@ You need to call an unmanaged function from your managed code by using Platform Invoke services. What should you do?
Create a class to hold DLL functions and then create prototype methods by using managed code.
 

StringBuilder V.S. String

Saturday, October 21, 2006

Code Access Security

CAS

@ When you run an unmanaged application in Windows 2003, XP or earlier, that code gets all the privileges your user account has. The application can do anything your user account has permissionos to do. so you are forced to log on with minimal privileges to restrict application permissions.

@ Code Access Security (CAS), a concept that .NET Framework introducted into Windows, enables users to restrict on a very granular level what managed application can do.

@ CAS allows administrators and developers to control applicatoin authorization similar to the way they have always been albe to authorize users.

@ Unfortunately, CAS can be applied only to managed applications that use the .NET Framework runtime. Unmanaged applications run without any CAS restrictions and are limited only by the operating system's RBS.

^ ASP.NET中的Membership和Role Management是对“人”(people, user)的权限管理(authentication和authorization);而CAS则是对“程序”(application,code)进行权限管理。

Evidence

@ Generally, a security system use the username, password, access control lists to identify users and determine what a user can and can't do. However, CAS identifies and assigns permissions to applications ratha than to people, thus, it identifies assembilies using evdience.
@ In CAS, evidence is used just like a person's passport, password, and PIN - information that proves identity and describes an individual as deserving a certain level of trust.

@ Each piece of evidence is a way that an assembly can be identified, such as the location (folder or website) where the assembly is stored and running, a hash of the assembly's code, or the assembly's digital signature.

@ There are 2 types of evidence: host evidence and assembly evidence:

  1. Host evidence describes the assembly's origin, such as the application directory, URL, or site; and also describes the assembly's identity, such as the hash, pulisher, or strong name.
  2. Assembly evidence are ones provided by custom user or developer.

^ I think evidence is the Authentication part of the security process for application or code, just like username and password are the Authentication for people or users.

Permission

@ A permission is a CAS access control entry.

^ A permission set is a CAS ACL (Access Control List).

Friday, October 20, 2006

What the fuck Callback is on earth? Define it!

To synchronize thread pool threads

@ Queue your task for execution by passing the WaitCallback delegate to ThreadPool.QueueUserWorkItem. Your callback method executes when a thread pool thread becomes available.

@ In many cases, creating your own thread is not necessary or suggested.
The threading system in .NET supports a built-in thread pool that can be used in many situations where you might expect to create your own threads.


e The Managed Thread Pool

Cleaning Up Unmanaged Resources

What you should NOT do in cleaning up unmanaged resoures!

  1. You should prevent users of your application from calling an object's Finalize method directly by limiting its scope to protected.
  2. You are strongly discouraged from calling a Finalize method for a class other than your base class directly from your application's code.

How to properly clean up unmanaged resources?

@ To properly dispose of unmanaged resources, it is recommended that you implement a public Dispose or Close method that executes the necessary cleanup code for the object.

@ The IDisposable interface provides the Dispose method for resource classes that implement the interface. Because it is public, users of your application can call the Dispose method directly to free memory used by unmanaged resources.
@ When you properly implement a Dispose method, the Finalize method becomes a safeguard to clean up resources in the event that the Dispose method is not called.

@ The IDisposable Interface defines a method to release allocated unmanaged resources.

Why do we need IDisposable?
  1. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used, however, it is not possible to predict when garbage collection will occur.
  2. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.

@ Thus, we should use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector.

@ The consumer of an object can call this method when the object is no longer needed.

@ When calling a class that implements the IDisposable interface, use the try-finally pattern to make sure that unmanaged resources are disposed of even if an exception interrupts your application.

@ Destructors are used to destruct instances of classes.

Using Destructors to Release Resources

@ In general, C# does not require as much memory management as is needed when developing with a language that does not target a runtime with garbage collection. This is because the .NET Framework garbage collector implicitly manages the allocation and release of memory for your objects.
When your application encapsulates unmanaged resources such as windows, files, and network connections, you should use destructors to free those resources. When the object is eligible for destruction, the garbage collector runs the object's Finalize method.

@ A class can only have one destructor.
@ Destructors cannot be inherited or overloaded.
@ Destructors cannot be called. They are invoked automatically.
@ A destructor does not take modifiers or have parameters.
@ Destructors cannot be defined in structs. They are only used with classes.

@ The programmer has no control over when the destructor is called because this is determined by the garbage collector.
The garbage collector checks for objects that are no longer being used by the application. If it considers an object eligible for destruction, it calls the destructor (if any) and reclaims the memory used to store the object.
Destructors are also called when the program exits.

e Implementing a Dispose Method

e Garbage Collection

e Cleaning Up Unmanaged Resources

Using MemberInfo of System.Reflection

@ You need to ascertain wheter a method named OneMethod is accessible to a derived class. What shoud you do?
^ Call the IsFamily property of the MethodInfo Class.

@ The IsFamily property gets a value indicating whether the visibility of this method or constructor is described by MethodAttributes.Family; that is, the method or constructor is visible only within its class and derived classes. (Inherited from MethodBase.)
^ Family Indicates that the method is accessible only to members of this class and its derived classes.

^ The MethodAttribute enumeration also contains:
Abstract Indicates that the class does not provide an implementation of this method.
Assembly Indicates that the method is accessible to any class of this assembly.
Final Indicates that the method cannot be overridden.
Private Indicates that the method is accessible only to the current class.
Virtual Indicates that the method is virtual
Static Indicates that the method is defined on the type; otherwise, it is defined per instance.

e You can read more about MethodAttributes's member here.

e About MethodInfo class

Thursday, October 19, 2006

Reflecting types

The Type class有什么用?

@ The Type class represents a single type, allowing you to look at the methods, properties, events, interfaces, and inheritance tree of a particular type in the system.

How to get the Type object?

@ You can get Type object in 4 ways:

  1. From the Assembly class
  2. From the Module class
  3. From the instance of an object
  4. Using keyword typeof in C# or GetType in VB.

@ 1st way: from the Assembly class:

Dim OneAssembly As Assembly = Assembly.GetExecutingAssembly()
Dim AssemblyTypes() As Type = OneAssembly.GetTypes()

@ 2nd way: from the Module class:

Dim AllModulesOfOneAssembly As [Module] = OneAssembly.GetModules()
Dim OneModuleOfOneAssembly As [Module] = AllModulesOfOneAssembly(0)
Dim AllTypesOfOneModuleOfOneAssembly () As Type = OneModuleOfOneAssembly .GetTypes()

@ 3rd way: get the type of the instance of an object by calling its GetType method:

Dim OneObject As New Object()
Dim TypeOfOneObject As Type = OneObject.GetType()

@ 4th way: create a Type object using C# typeof / VB GetType keywork:

Dim OneSpecificType As Type = GetType(Int32) 'VB

Type OneSpecificType = typeof(Int32) //C#

Monday, October 16, 2006

What is Property, on earth?

@ Properties can be considered smarter fields in that they can be assigned to or read from (like a field), yet when this happens some code in the class executes, and therefore the author of the class can process the value being assigned or returned.

@ Inside the Property block, you write a Get…End Get block, which defines which value the property returns, and a Set…End Set block, which defines how values are assigned to the property.

@ In most cases, a property simply maps to a Private field, so the code for these two blocks often looks like this:

Dim m_BirthDate As Date
Public Property BirthDate() As Date
Get
Return m_BirthDate
End Get
Set(ByVal value As Date)
m_BirthDate = value
End Set
End Property

Saturday, October 14, 2006

About Microsoft .NET Framework 3.0

The Microsoft .NET Framework version 3.0 (formerly known as WinFX) is the new managed-code programming model for Windows. It combines the power of .NET Framework 2.0 with new technologies for building applications that have a visually compelling user experience, seamless communication across technology boundaries, and support for a wide range of business processes.

All of the classes that represent the new components (WPF, WF, WCF, and CardSpace) are part of the System namespace. The core classes of the .NET platform, such as the common language runtime (CLR) and base class libraries (BCL) remain as they are in .NET Framework 2.0.



How .NET Framework 3.0 Relates to .NET Framework 2.0 and Earlier
The .NET Framework 3.0 adds new technologies to the .NET Framework 2.0, which makes the .NET Framework 3.0 a superset of the .NET Framework 2.0. You can think of .NET Framework 3.0 as an "additive" release to the .NET Framework 2.0, as contrasted with a generational release where software is revised across the board. (For example, the .NET Framework 2.0 was a generational release over the .NET Framework 1.0.)

Because .NET Framework 3.0 is an additive release and uses the core run-time components from .NET Framework 2.0, it is completely backward compatible with the earlier version. Your existing .NET Framework 2.0 based-applications will continue to run without any modifications and you can safely continue your investments using the technologies that shipped with .NET Framework 2.0.

Installing the .NET Framework 3.0
The .NET Framework 3.0 is installed by default on Microsoft Windows Vista. On Microsoft Windows Server code-named "Longhorn", you can install the .NET Framework as a Windows Feature using Roles Management tools. On Windows XP and Windows Server 2003, installing .NET Framework 3.0 also adds any .NET Framework 2.0 components that are not already installed.
If .NET Framework 2.0 is already installed, the .NET Framework 3.0 installer adds only the files for Windows Presentation Foundation (WPF), Windows Workflow Foundation (WF), Windows Communication Foundation (WCF), and Windows CardSpace.

Components shared with .NET Framework 2.0 are installed in the following location:%windir%\Microsoft.NET\Framework\V2.0.50727
Components that are new to .NET Framework 3.0 are installed in the following location: %windir%\Microsoft.NET\Framework\V3.0
All components of the .NET Framework 3.0 reference assemblies are installed in the following location: %programfiles%\Reference Assemblies\Microsoft\Framework\v3.0

Uninstalling .NET Framework 3.0 will not remove the components shared with .NET Framework 2.0. To remove those components, you must first uninstall .NET Framework 3.0 and then separately uninstall .NET Framework 2.0.

Version Numbers for .NET Framework Assemblies
The .NET Framework 3.0 shares many components with .NET Framework 2.0, and the common language runtime (CLR) and base class libraries are the same as those in .NET Framework 2.0. Therefore, these shared components stay at version 2.0.

The version number 3.0 applies to all runtime and reference assemblies for Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), Windows Workflow Foundation (WF), and Windows CardSpace.

^ 基本上对我没有什么影响,因为我目前只关心Internet Application。所以,用好ASP.NET 2.0就是首要的。集中力量,先不去管.NET Framework 3.0的其他部分。

Wednesday, October 11, 2006

Globalization: Culture, Region, Date, Number

@ How to detect a user's current culture information?
Using the CurrentCulture property of the executing thread's CurrentThread property. i.e.,
Dim UserCulture As CultureInfo = Thread.CurrentThread.CurrentCulutre
Console.WriteLine("The current culture of this application is : " & UserCulutre.Name)

@ How to set the current culture?
Just specify a different value to the CurrentCulture property of the CurrentThread property of the Thread class. i.e.,
Thread.CurrentThread.CurrentCulutre = New CultureInfo("es-VE")

@ The RegionInfo class provides specific information about a particular country or region.

@ The DateTimeFormatInfo class provides a comprehensive set of methods and properties to handle and respond to the dates of different culutres.
Dim UserCulture As CultureInfo = New CultureInfo("zh-CN")
Dim Days() As String = UserCulture.DateTimeFormat.DayNames
For Each Day As String In Days
Console.WriteLine("Culture : " & UserCulture.Name)
Console.WriteLine("Day Name : " & Day)
Next

Tuesday, October 10, 2006

About VB.NET Procedure / Method

@ A procedure is a block of Visual Basic statements enclosed by a declaration statement (Function, Sub, Operator, Get, Set) and a matching End declaration. All executable statements in Visual Basic must be within some procedure.

@ Types of Procedures
Visual Basic uses several types of procedures:
· Sub Procedures perform actions but do not return a value to the calling code.
· Event-handling procedures are Sub procedures that execute in response to an event raised by user action or by an occurrence in a program.
· Function Procedures return a value to the calling code. They can perform other actions before returning.
· Property Procedures return and assign values of properties on objects or modules.
· Operator Procedures define the behavior of a standard operator when one or both of the operands is a newly-defined class or structure.
· Generic Procedures in Visual Basic define one or more type parameters in addition to their normal parameters, so the calling code can pass specific data types each time it makes a call.

Reflection到底是个啥东西?

@ Code in the CLR is packaged in an assembly. Even though it is often thought of as a file, an assembly is actually a logical container for different parts of the data the CLR needs to execute code.

@ These parts of data of an assembly include: Assembly metadata, Type metadata, Intermediate Language code, and Resources.

@ Assembly Metadata includes data that defined the assembly, such as the name, version, strong name, and culture information. Assembly metadata is also called manifest.

@ Type Metadata is the information describes what a type looks like, including the namespace, class name, members (methods, properties, constructors, etc.), and parameters.

@ Most of the time, all these parts of an assembly are compiled into a single file.

@ Assemblies are containers for modules, and modules are containers for types.

^ 我啥时候会用的上Reflection呀?

e C-sharp reflection: Save development time throughout the project life-cycle

Monday, October 09, 2006

Callback

Saturday, October 07, 2006

The constructor method of VB.NET

A constructor is a method that runs when a new instance of the class is created.
In Visual Basic, the constructor method is always named Sub New:


Class Person
Private CreateTime As Date
Sub New()
' Display a diagnostic message.
Console.WriteLine("A new instance of Person is being created.")
' Remember when this instance was created.
CreateTime = Now
' Perform other initialization chores.

End Sub
End Class