Showing posts with label Class Library. Show all posts
Showing posts with label Class Library. Show all posts

Monday, October 30, 2006

Dealing with IO in ASP.NET envirenment

d When your code is excuted by IIS, it executes under the context of ASP.NET Worker Process user account (ASP.NET) , therefore, your application may be restricted by that account's security rights.

d By deafult, the ASP.NET Worker Process does not have rights to write to the local disk.

^ What the ASP.NET Worker Process is allowed to do inside of the IO namespace?

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

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

Sunday, September 24, 2006

.NET : Threading

Why and when to use multithreading?

@ For most developers, the primary motivation for multithreading is the ability to perform long-running tasks in the background, while still providing the user with an interactive interface.
Another common scenario is when building server-side code that can perform multiple long-running tasks at the same time, thus, each task can be run on a separate thread, allowing all the tasks to run in parallel.

@ If we regard computer programs as being either application software or service software:
Application software uses multithreads primarily to deliver a better user experience.
Service software uses multithreads to keep CPU busy servicing and deliver scalability.

@ For interactive applications, multithreading is not a way to improve performance, but rather is a way to improve then end user experience by providing the illusion that the computer is executing more code simultaneously.
In the case of server-side code, multihtreading enables higher scalability by allowing Windows to better utilize the CPU along with other subsystems such as IO.

What the fuck is thread?

@ The term thread is short for thread of execution.
When your program is running, the CPU is actually running a sequence of processsor instructions, one after another. You can think of these instructions, one after another, as forming a thread that is being executed by the CPU.

What is process?

@ Each of the programs your computer keeps in memory runs in a single process. A process is an isolated region of memory that contains a program's code and data. The process is started when the program starts and exists for as long as the program is running.

@ When a process is started, Windows sets up an isolated memory area for the program and loads the program's code into that area of memory. It then starts up the main thread for the process. The mean thread might execute instructions taht create more threads within the same process.

.NET : Genric Collection

^ 对于Generic Dictionary的程序写法:

Dim OneGenericDictionary As New Dictionary(Of Integer, String)
OneGenericDictionary.Add(1, "One")
OneGenericDictionary.Add(2, "Two")
OneGenericDictionary.Add(3, "Three")

For Each OnePare As KeyValuePair(Of Integer, String) In OneGenericDictionary
Console.WriteLine("The pare is {0} : {1}", OnePare.Key.ToString, OnePare.Value.ToString)
Next

Dim OneEnumerator As Dictionary(Of Integer, String).Enumerator = OneGenericDictionary.GetEnumerator()
While OneEnumerator.MoveNext
Console.WriteLine(OneEnumerator.Current.Key & " : " & OneEnumerator.Current.Value)
End While

Saturday, September 23, 2006

.NET Collection

ArrayList

@ ArrayList, like most collections, supports several ways to iterate over its contents.
Dim OneArrayList As ArrayList = New ArrayList()
OneArrayList.Add("First")
OneArrayList.Add("Second")
OneArrayList.Add("Three")
OneArrayList.Add("Four")
'Way #1

For Each OneArrayListItem As Object In OneArrayList
Console.WriteLine(OneArrayListItem.ToString)
Next
'Way #2

Dim OneEnumerator As IEnumerator = OneArrayList.GetEnumerator()
While OneEnumerator.MoveNext()
Console.WriteLine(OneEnumerator.Current)
End While
'Way #3

For Indexer As Integer = 0 To OneArrayList.Count - 1
Console.WriteLine(OneArrayList(Indexer))
Next

Dictionary

^ 有两种Standard Dictionary:HashtableSortedList,三种Specialized Dictionary:ListDictionaryHybridDictionaryOrderedDictionary

@ In general, the Hashtable class is a very efficient collection. The only problem with Hashtable is for small collections (fewer than 10 elements) it impede performance. This is where ListDictionary comes in.
@ When you know our collection is small, use a ListDictionary; when your collection is large, use a Hashtable. But what if you just do not know how large your collection is? Use HybridDictionary!
^ 干吗非得整得这么复杂?TNND,让事情简洁明了不行?我就不信性能会差十万八千里。硬件的强大处理能力不知有多少被浪费掉了!何不只用一种Dictionary来满足所有类似需求?HybridDictionary解决了所谓的HashtableListDictionary的efficiency问题。有什么意义?对于efficiency这一点我不太考虑,只当是存在Hashtable一种Dictionary就行了。

@ To accomodate you when you need a fast Dictionary but also need to keep the items in an ordered fashion, the .NET Framework supports the OrderedDictionary.
^ OrderedDictionary除了具备Hashtable的功能之外,还具备了control the order of the elements in the collection的功能。OrderedDirctionry is as if a mix of an ArrayList and a Hashtable. 所以,为了简单起见,作为一种通用解决方案,对于需要Dictionary功能的地方,我就只使用OrderedDictionary,只有有明确需求的时候在研究使用其他的Dictionary.
^ 可是,MD!我发现HashtableContainsKey()ContainsValue()两个method,可是OrderDictionary没有。虽然OrderDictionry.Contains(Key)可以实现Hashtable.ContainsKey()的功能,却实现不了 Hashtable.ContainsValue()

^ 也许应该考虑尽量使用Generic Collection吧。还没有研究透。

Friday, September 22, 2006

.NET : Serialization

What is serialization?

@ Serialization is the process of converting an object into a stream of bytes in order to persist it to memory, a database, or a file.

Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
The object is serialized to a stream, which carries not just the data, but information about the object's type, such as its version, culture, and assembly name.

@ Hah hah, teleportation in science fiction is a good example of serialization, although which is not currently supported by .NET Framework. ;-)

Why use serialization?

@ The two most important reasons are:
to persist the state of an object to a storage medium so an exact copy can be re-created at a later stage,
to send the object by value from one application domain to another.

Scenarioes of using serialization

@ Through serialization, a developer can perform actions like
1. send the object to a remote application by means of a Web Service,
2. pass an object through a firewall as an XML string,
3. maintain security or user-specific information across applications.
4. save session state in ASP.NET
5. copy objects to the Clipboard in Windows Forms
6. pass objects by value from one application domain to another, used by Remoting.

How to serialize and unserialize?

@ How to serialize an object?
At a high level, the steps are:
1. Create a Stream object, to hold the serialized output.
2. Create a BinaryFormatter object, to do serialize work.
3. Call the BinaryFormatter.Serialize method to serialize the object and output the result to the stream.
Dim DataToBeSerialized As String = "This is the content to store in a file."
Dim FileStreamForHolding As FileStream = New FileStream("SeriaziedString.Data", FileMode.Create)
Dim OneBinaryFormatter As BinaryFormatter = New BinaryFormatter
OneBinaryFormatter.Serialize(FileStreamForHolding , DataToBeSerialized)
FileStreamForHolding .Close

@ How to deserialize an object?
At a high level, the steps are:
1. Create a Stream object, to read the serializd output.
2. Create a new object to store the deserialized data.
3. Create a BinaryFormatter object.
4. Call the BinaryFormatter.Deserialize method to deserialized the object, and cast it to the correct type.
Dim FileStreamForReading As FileStream = New FileStream("SerializedString.Data", FileMode.Open)
Dim ObjectToStore As String = ""
Dim BinaryFormatterWorking As BinaryFormatter = New BinaryFormatter
ObjectToStore = CType(BinaryFormatterWorking.Deserialized(FileStreamForReading), String)
FileStreamForReading.Close

@ It is a good practice to make ALL calsses serializable enven if you do not immediately require serialization.

@ To create a class that can be serialized, add the Serializable attribute.

Wednesday, September 20, 2006

Enumeration是个好东西

@ Enumerations are related symbols that have fixed values.
@ The purpose of enumerations is to simplify coding and improve code readability by enabing you to use meaningful symbols instead of simple numeric values.
@ How to creat Enumerations? For instance:
Enum Titles As String
Mr
Ms
Mrs
Dr
Jr
End Enum

关于Double的四舍五入

I. 在VB.NET 2005中,根本就没有四舍五入这个概念。round()不应该被翻译成四舍五入。

II.如何实现四舍五入?
一个同事告诉我一个方法:比如要将一个Double保留到小数点后两位并且四舍五入,那么就把这个Double加上0.005,然后截断到小数点后两位。他说这个方法曾经在很多项目里面用过,没问题。我没仔细测试过,但是想想看,道理上是讲的过去的。

.NET System.IO

d The file system classes are separated into two types of classes: informational and utility.
d The informational classes include: FileInfo, DirectoryInfo, DriveInfo. These classes expose all the system information about file system objects - files, directories, and drives.
d The utility classes include: File, Directory, and Path. These classes provide static/shared methods to perform certain operations on file system objects - files, directories, and paths.

d The Path class deals only with the string of a path. It makes no changes to the file sytem. For instance:
Dim OnePath As String = "C:\boot.int"
Path.ChangeExtention(OnePath, "bak")
^ 以上代码改变了一个Path,但是并没有改变文件名本身,就是说,OnePath改变成"C:\boot.bak",但是boot.ini本身的文件名并没有被改变。

How to read from a file:

1. One way of reading a file is using StreamReader classes, which makes reading easier than calling the Read or ReadByte methods of the Stream class.
Dim OneFile As FileStream = File.Open("C:\boot.ini", FileMode.Open, FileAccess.Read)
Dim OneReader As StreamReader = New StreamReader(OneFile)
Console.Write(OneReader.ReadToEnd())
OneReader.Close()
OneFile.Close()

@ The StreamReader class is intented to read a stream as a string, not as a series of bytes. Thus, the StreamReader's methods for returning data all return either strings or arrays of strings.

2.The File class has a simpler way to open a file for reading. It supports creating a StreamReader directly with the OpenText method:
Dim OneReader As StreamReader = File.OpenText("C:\boot.int")
Console.Write(OneReader.ReadToEnd())
OneReader.Close()

3. If all you need to do is read out the entire file, the File class supports reading the file in a single method call, hiding all the details of the stream and reader implementation by calling its ReadAllText method:
Console.Write(File.ReadAllText("C:\boot.ini"))

How to create a file for writing:

1. We can use the StreamWriter to write text directly into a new file
Dim OneFile As FileStream = File.Create("C:\SomeFile.txt")
Dim OneWriter As StreamWriter = New StreamWriter(OneFile)
OneWriter.WriteLine("Hello")
OneWriter.Close()
OneFile.Close()

2. File class supports creating a StreamWriter object directly with the CreateText method:
Dim OneWriter As StreamWriter = File.CreateText("C:\SomeFile.txt")
OneWriter.WriteLine("Hello")
OneWriter.Close()

3. File class aslo supports the WriteAllText method that write a string to a new file:
File.WriteAllText("C:\SomeFile.txt", "Hello")

How to open an existing file for writing:

1. File class
Dim OneFile As FileStream = File.Open("C:\SomeFile.txt", FileMode.Open, FileAccess.Write)

2. The File class has the OpenWrite method, which is a shortcut for opening existing files for writing:
Dim OneFile = File.OpenWrite("C:\SomeFile.txt")

How to exither open an existing file or create a new file for writing:

1. Using the Open method of the File class to specify that you want open or create. The FileMode.OpenOrCreate enumeration value allows you to avoid writing procedural code to deal with the issue of whether you are dealing with a new or existing file:
Dim OneFile As FileStream = FileOpen("C:\SomeFile.txt", FileMode.OpenOrCreate, FileAccess.Write)

Tuesday, September 19, 2006

.NET : Generics

@ Why use Generics?
Develpers used the Object class for parameters and members, and would cast other classes to and from the Object class.
1. Using generics allows the comipler to catch type errors before your program runs, namely, its' type-safe.
2. Using generics doesn't require casting or boxing, which improves run-time performance.

@ .NET built-in generic types inludes:
1. Nullable
2. EventHandler
3. System.Collection.Generic, including Dictionary, Queue, SortedDictionary, and SortedList.

^ Generic应该就是被看成是一个语言特性。它诞生了,成为了一种语言的feature,目的是用来解决从前的写法的问题。所以,就应该完全抛弃掉从前的写法,使用Generic这个语言特性。无论是Collection还是自己写的东西。对我个人来说,以后所有的程序都将全盘使用Generic这种思想和特性,消除type-safe问题,也让程序更简洁漂亮一些。

Monday, September 18, 2006

.NET : Value Types

@ Built-In types are base types provided with the .NET Framework, with which other types are built.

@ Value types directly contain their data, offering excellent performance. However, value types are limited to types that store very small pieces of data. In the .NET Framework, all value types are 16 bytes or shorter.

@ All build-in numeric types are value types.

@ For integral variables, use Int32 and UInt32, because the runtime optimizes the performance of 32-bit integer types (System.Int32 and System.UInt32).
@ For floating-point operations, System.Double is the most efficient type, because those operations are optimized by hardware.

@ User-Defined types are also called structures. Structures are a composite of other types that make it easier to work with related ata.

@ Instances of User-Defined types are stored on the stack and they contain their data directly.

@ In most ways, structures behave nearly identical to classes. While the functionality is similar, structures are usually more efficient than classes.

@ Enumerations are related symbols that have fixed values. Use enumerations to provide a limited set of of choices for a value. For example:

Enum Titles As Integer
Mr
Ms
Mrs
Dr
End Enum

@ The purpose of enumerations is to simplify coding and improve code readability by enabling you to use meaningful symbols instead of simple numeric values.

Sunday, September 17, 2006

.NET XmlReader & XmlWriter

@ XmlReader provides fast, forwar-only, read-only access to XML documents.

@ The primary way for you to create an instance of an XmlReader is by using the Static/Shared Create method. Rather than creating concrete implementattions of the XmlReader calss, you create an instance of the XmlReaderSettings class and pass it to the Create method. You specify the features you want for your XmlReader object with the XmlReaderSettings class.

@ If you’re going to run through the document only once, you don’t want to hold it in memory; youwant the access to be as fast as possible. XmlReader is the right decision in this case.

^ 我倾向于在一个Application中,对于数据操作,XML操作,都分别只使用在一种模式:数据操作使用DataSet;XML操作使用XmlDocument。虽然Reader和Writer的模式有优势,但是并不提供一个完整的解决模型和统一的操作方式。只使用一种“全能”的模式,可以让编程更易于实现和维护。至于内存和性能问题,我想应该通过硬件来解决。