10월, 2013의 게시물 표시

IExtensibleDataObject for Versioning round-trip problem

This situation of new-old-new interaction is called a versioning round-trip. WCF supports handling of versioning round-trips by allowing a service (or client) with knowledge of only the old contract to simply pass through the state of the members defined in the new contract without dropping them. The problem is how to enable services/clients that are not aware of the new members to serialize and deserialize those unknown members without their schemas, and where to store them between calls. WCF’s solution is to have the data contract type implement the IExtensibleDataObject interface

Versioning problem.

만약 Endpoint끼리 DataContract에 미스매치가 있을 경우를 대비해, 꼭 필요한 DataMember에 IsRequired=true 를 세팅한다. 그렇게 하면 콜 하다  NetDispatcherFaultException 익셉션이 발생한다.

Known Types and Service Known Types

Endpoint 사이의 메세지 직렬화때문에, 객체의 자동형변환이 가능하지 않다. 가능하게 하기 위해서는 명시적으로 derived 타입을 알려줘야 한다. The solution is to explicitly tell WCF about the Customer class using the KnownTypeAttribute, defined as: [AttributeUsage(AttributeTargets.Struct|AttributeTargets.Class, AllowMultiple = true)] public sealed class KnownTypeAttribute : Attribute { public KnownTypeAttribute(Type type); //More members } [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)] public sealed class ServiceKnownTypeAttribute : Attribute { public ServiceKnownTypeAttribute(Type type); //More members } WCF lets you configure the known types in the service’s or client’s config file, as shown in Example 3-6. You need to provide not just the type names, but also the names of their containing assemblies. When not relying on string name or assembly version resolution, you can just use the assembly-friendly name: Or use Data Contract R...

Shared Data Contracts

When adding  a  service reference in Visual Studio 2010, you must provide a unique namespace for each service reference. The imported types will be defined in that new namespace. This presents a problem when adding references for two different services that share the same data contract, since you will get two distinct types in two different namespaces representing the same data contract. By default, however, if any of the assemblies referenced by the client has a data contract type that matches a data contract type already exposed in the metadata of the referenced service, Visual Studio 2010 will not import that type again. It is worth emphasizing again that the existing data contract reference must be in another referenced assembly, not in the client project itself. This limitation may be addressed in a future release of Visual Studio, but for now, the workaround and best practice is obvious: factor all of your shared data contracts to a designated class library, and ha...

Service Contract Factoring and Design

Syntax aside, how do you go about designing service contracts?  How do you know which operations to allocate to which service contract?  How many operations should each contract have?  Answering these questions has little to do with WCF and a lot to do with abstract service-oriented analysis and design.

Contract Inheritance

Service contract interfaces can derive from each other, enabling you to define a hierarchy of contracts. However, the ServiceContract attribute is not inheritable . Consequently, every level  in the interface hierarchy must explicitly have the  Service Contract attribute. And the host can expose a single endpoint for the bottommost interface in the hierarchy. 아항~

WCF architecture

이미지

Generating the client config file. Do not rely on the auto-generated client config file.

Juval Lowy  said that I recommend never letting SvcUtil or Visual Studio 2010 control the config file. Nevertheless SvcUtil http://localhost:8002/MyService/ /out:Proxy.cs /config:App.Config SvcUtil http://localhost:8002/MyService/ /out:Proxy.cs /noconfig

WCF Architecture

이미지

Encryption in .NET

Symmetric Encryption Aes DES RC2 Rijndael TripleDES Asymmetric Encryption DSA ECDiffieHellman ECDsa RSA

SHA and MAC

SHA If you want to ensure that the data is not tampered with, you can use a Secured Hash Algorithm(SHA) MAC for authenticity of the data you can use a Message Authentication Code(MAC) algorithm

Instrumenting Applications

Instrumenting a program means adding features to it to study the program itself. Usually that means adding code to monitor performance, record errors, and track program execution. With good instrumentation, you can tell what an application is doing and identify performance bottlenecks without stepping through the code in the debugger.

Debug, Trace 객체는 어떤 빌드에서 활성화되나?

가 아니라, DEBUG 심볼이 정의되어 있냐에 달려있다. 보통 기본 빌드인 Debug에 DEBUG 심볼이 기본 등록되어 있어서 쉽게 하는 착각.

Preprocessor directive중 #line

#line 10000 #line default #line hidden ~ #line default | N

이쯤에서 다시 보는 Command 타입

ExecuteNonQuery ExecuteReader ExecuteScalar ExecuteXmlReader The ExecuteScalar method is used when you know that your resultset contains only a single column with a single row . 요건 미처 몰랐넹.

Attributes add metadata to your program

Attributes add metadata to your program.  Metadata  is information about the types defined in a program.  객체가 아니라, 타입에 대한 메타데이타다. 자꾸 헷갈리네.

How to: Declare, Instantiate, and Use a Delegate

In C# 1.0 and later, delegates can be declared as shown in the following example. C# // Declare a delegate.  delegate   void Del( string str); // Declare a method with the same signature as the delegate.  static   void Notify( string name) { Console.WriteLine( "Notification received for: {0}" , name); } C# // Create an instance of the delegate. Del del1 = new Del(Notify); C# 2.0 provides a simpler way to write the previous declaration, as shown in the following example. C# // C# 2.0 provides a simpler way to declare an instance of Del. Del del2 = Notify; In C# 2.0 and later, it is also possible to use an anonymous method to declare and initialize a  delegate , as shown in the following example. C# // Instantiate Del by using an anonymous method. Del del3 = delegate ( string name) { Console.WriteLine( "Notification received for: {0}" , name); }; In C# 3.0 and...

Alternatives about the ThreadPool class.

Task Parallel Library( TPL ) Asynchronous Pattern Model( APM ) Task-based Asynchronous Pattern Model( TAP ) Event based Asynchronous Pattern( EAP ) async / await keywords

In .NET all applications have several threads.

Garbage Collector thread Responsible for the garbage collection. Finalizer thread Responsible to run the Finalize method of your objects. Main thread Responsible to run your main application’s method. UI thread If your application is a Windows Form application, a WPF application, or a Windows store application, it will have one thread dedicated to update the user interface.

Which of the following statements about inheritance and events is false?

A derived class can raise a base class event by using code similar to the following: if (base.EventName != null) base.EventName(this, args); A derived class cannot raise an event defined in an ancestor class. A class can define an OnEventNamemethod that raises an event to allow derived classes to raise that event. A derived class inherits the definition of the base class’s events, so a program can subscribe to a derived object’s event. Good question.

Rethrow the current exception

To rethrow the current exception, use the throwstatement without passing it an exception. The following code snippet demonstrates this technique: try { // Do something dangerous. } catch (Exception) { // Log the error. // Re-throw the exception. throw; } Contrast this code with the following version: try { // Do something dangerous. } catch (Exception ex) { // Log the error. // Re-throw the exception. throw ex; } 둘의 차이는?

Exception properties

Data A collection of key/value pairs that give extra information about the exception . HelpLink A link to a help file associated with the exception . HResult A numeric code describing the exception . InnerException An Exceptionobject that gives more information about the exception .Some libraries catch exceptions and wrap them in new exception objects to provide information that is more relevant to the library .In that case, they may include a reference to the original exception in the InnerExceptionproperty . Message A message describing the exception in general terms . Source The name of the application or object that caused the exception . StackTrace A string representation of the program’s stack trace when the exception occurred . TargetSite Information about the method that threw the exception .

Convention about Event in .NET

accessibility event EventHandler<XXX EventArgs > XXX; 상속클래스를 위해서는 protected virtual void On XXX(XXX EventArgs args) {      if (XXX != null) XXX(this, args); } 를 정의해서, 상속클래스가 이벤트를 일으킬 수 있도록 해야 한다. 빨간색은 convention 이다.

ASP.NET 4.5 새 기능

모델 바인딩이 특히 맘에든다. asp.net 4에서는 MVC3에만 있어서 아쉬웠는데. 그리고 나도 한때에는 웹폼을 혐오했는데, 웹폼의 생산성만큼은 이제 인정해야 할 듯. The following table lists some of the enhancements that have been made for Web Forms in ASP.NET 4.5. Feature Description Resources Model binders Web Forms now supports  model binding , which lets you bind data controls directly to data-access methods. ASP.NET automatically converts data from form fields, query strings, cookies, session state, and view state into method parameters. You can use these parameters to select data from or make updates to the database. (This technique is similar to model binding in ASP.NET MVC.) Model Binding and Web Forms  (tutorial series) Model Binding  (What's New whitepaper) Model Binding Part 1 - Selecting Data  (video) Model Binding Part 2 - Filtering  (video) Strongly typed binding expressions in data controls You can now write strongly typed, two-way data-binding expressions in Web Forms data con...

GC는 메모리가 부족할 때(쯤) 실행된다.

실행되면, 안 쓰이는 객체들의 Finalization을 실행. 이것이 바로 nondeterministic finalization. 그래서 IDisposable을 통해서 명시적으로 정리작업을 해야 한다. 또한 IDisposable.Dispose()는 여러 번 호출되도 문제가 되지 않아야 하므로, 내부적으로 정리 작업이 실행됐는 지에 대한 상태값을 가지고 있어야 한다. The following list summarizes the resource management rules and concepts: If a class contains no managed resources and no unmanaged resources, it doesn’t need to implement IDisposableor have a destructor.  If the class has only managed resources, it should implement IDisposablebut it doesn’t need a destructor. (When the destructor executes, you can’t be sure managed objects still exist, so you can’t call their Disposemethods anyway.) If the class has only unmanaged resources, it needs to implement IDisposableand needs a destructor in case the program doesn’t call Dispose. The Disposemethod must be safe to run more than once. You can achieve that by using a variable to keep track of whether it has been run before. The Disposemethod should free both managed and unmanaged re...

BEST PRACTICES: Provide Equatable

Generic collection classes such as List, Dictionary, Stack, and Queue provide Contains and other methods that compare objects for equality. Microsoft recommends that any class that you are likely to place in one of these generic collections should implement IEquatable. IEquatable 은 좀 뜻밖이군.