2013의 게시물 표시

Bind나 Eval 의 포맷문자열안에 single quot 넣기.

속성='<%# String.Format("{0}\"aaa\"aa{1}", Eval("aa"), Eval("bb"), Eval("cc")) %>' 이렇게 해보자.

왜 Web 컨트롤 <asp:HiddenField 에는 커스텀 HTML 속성이 추가 안 될까?

왜 안 되게 했을까나? 다른 Web 컨트롤은 되면서... 대신 <input type="hidden" runat="server" ... > 이렇게 HTML 서버 컨트롤을 쓰면 된다.

WebForm 컨트롤 종류

이미지
이쯤에서 보는 서버 컨트롤 종류.

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

Martin Fowler said.

How to: Create Instances of ASP.NET User Controls Programmatically

Create Instances of ASP.NET User Controls Programmatically 흠... 유저컨트롤 별로 쓸 일 없어 보여서 공부 안 했는데 딱 걸렸다. ㅠㅠ.

Isolated Applications

Isolated Applications Developers are encouraged to design isolated applications and to update existing applications into isolated applications for the following reasons: Isolated applications are more stable and reliably updated because they are unaffected by the installation, removal, or upgrading of other applications on the system. Isolated applications can be designed so that they always run using the same assembly versions with which they were built and tested. Isolated applications can use functionality provided by the side-by-side assemblies made available by Microsoft. For more information, see Supported Microsoft Side-by-side Assemblies. Isolated applications are not tied to the shipping schedule of their side-by-side assemblies because applications and administrators can update the configuration after deployment without having to reinstall the application. This would not apply in the case where only one version of the assembly is being made available. A fully isolat...

Controlling Rendering

WPF provides three mechanisms for customizing how the source value is received and displayed, so you don’t need to give up the benefits of data binding to get the desired results in more customized scenarios. These mechanisms are string formatting, data templates, and value converters. String Formatting . Many controls have a XXXStringFormat property StringFormat ContentStringFormat ItemStringFormat HeaderStringFormat ColumnHeaderStringFormat Data Templates ContentTemplate ItemTemplate HeaderTemplate SelectedContentTemplate DetailsTemplate RowDetailsTemplate RowHeaderTemplate ColumnHeaderTemplate CellTemplate CellEditingTemplate HierarchicalDataTemplate Value Converter s morph a source value into a completely different target value Bridging Incompatible Data Types Customizing Data Display

Sharing the Source with DataContext

When encountering a Binding without an explicit source object, WPF traverses up the logical tree until it finds a non-null DataContext. 참 좋은 생각이다.

Binding's RelativeSource

Another way to specify a data source is by using Binding’s  RelativeSource property, which refers to an element by its relationship to the target element. The property is of type RelativeSource, which also happens to be a markup extension. Here are some of the ways RelativeSource can be used: Self, TemplatedParent, (nth)FindAncestor, PreviousData , etc. RelativeSource MarkupExtension

IoC container 성능 비교

http://www.palmmedia.de/blog/2011/8/30/ioc-container-benchmark-performance-comparison NInject 이 생각보단 느리네.

DataTable의 컬럼에 담을 수 있는 타입들은?

Setting the DataType value is very important to guaranteeing the correct creation and updating of data in a data source. The DataType property supports the following base .NET Framework data types: Boolean Byte, Byte[] Char DateTime Decimal Double Guid Int16 Int32 Int64 SByte Single String TimeSpan UInt16 UInt32 UInt64 Object 타입이라 다 담을 수 있는 줄 알았넹. ㅋ. DataColumn.DataType Property

Accessing Resources at the Site of Origin

Binary Resources (Logical) Resources These are arbitrary .NET objects stored (and named) in an element’s Resources property. It’s a fundamental piece of enabling software to be localized into different languages. It also enables higher productivity for developing software because the logical resources support enables you to consolidate information that might otherwise be duplicated , and even factor XAML files into more manageable chunks. Although full-trust applications can hard-code a uniform resource locator (URL) or path for loose binary resources, taking advantage of the site of origin notion is a more maintainable approach. (In addition, it is required for partial-trust applications.) The site of origin gets resolved to different places at runtime, depending how the application is deployed: For a full-trust application installed with Windows Installer, the site of origin is the application’s root folder. For a full-trust ClickOnce application, the site of origin is...

Property Paths in WPF

DisplayMemberPath supports syntax known as a property path that is used in several areas of WPF, such as data binding and animation. The basic idea of a property path is to represent a sequence of one or more properties that you could also use in procedural code to get a desired value. The simplest example of a property path is a single property name, but if the value of that property is a complex object, you can invoke one of its own properties (and so on) by delimiting the property names with periods, as in C#. This syntax even supports indexers and arrays.

Genuine Controls in WPF

Content controls Buttons Button RepeatButton ToggleButton CheckBox RadioButton Simple containers Label ToolTip Frame Containers with headers GroupBox Expander TabItem Items controls Selectors ComboBox ListBox ListView TabControl DataGrid Menus Menu ContextMenu TreeView ToolBar StatusBar Range controls ProgressBar Slider Everything else

How can I programmatically click a Button?

Button, like many other WPF controls, has a peer class in the System.Windows.Automation.Peers namespace to support UI Automation: ButtonAutomationPeer. It can be used as follows with a Button called myButton: ButtonAutomationPeer bap = new ButtonAutomationPeer(myButton); IInvokeProvider iip = bap.GetPattern(PatternInterface.Invoke) as IInvokeProvider; iip.Invoke(); // This clicks the Button These UI Automation classes have several members that are extremely useful for automated testing and accessibility.

Persisting and Restoring Application State

Isolated Storage A standard Windows application can have full access to the computer (depending on user security settings), so there are many options for storing data, such as using the Windows Registry or the local file system. But an attractive alternative to these classic approaches is to use the .NET Framework’s isolated storage technology. Besides being easy to use, the same techniques work in all environments in which managed code can run, such as in a Silverlight application or a XAML Browser Application (covered later in this chapter). For desktop apps, isolated storage is a data storage mechanism that provides isolation and safety by defining standardized ways of associating code with saved data. Standardization provides other benefits as well. Administrators can use tools designed to manipulate isolated storage to configure file storage space, set security policies, and delete unused data. With isolated storage, your code no longer needs unique paths to specify safe locat...

How can I create a single-instance application using WPF?

Mutex  : Mutual Exclusion, single-instance behavior The classic approach to implementing single-instance behavior still applies to WPF applications: Use a named (and, therefore, operating system-wide) mutex. The following code shows how you can do this in C#: bool mutexIsNew; using (System.Threading.Mutex m = new System.Threading.Mutex(true, uniqueName, out mutexIsNew)) { if (mutexIsNew) // This is the first instance. Run the application. else // There is already an instance running. Exit! } Just be sure that uniqueName won’t be chosen by other applications! It’s common to generate a globally unique identifier (GUID) at development time and use that as your identifier. Of course, nothing prevents a malicious application from creating a semaphore with the same name to prevent such an application from running! It is often desirable to communicate the command-line arguments to the running instance rather than silently exiting the duplicate instance. The only functionalit...

How do I retrieve command-line arguments in my WPF application?

Command-line arguments are typically retrieved via a string array parameter passed to Main, but the common way to define WPF applications doesn’t allow you to implement the Main method. You can get around this in two different ways. One way is to forgo defining an Application-derived class in XAML, so you can manually define the Main method with a string array parameter.  The easier way, however, is to simply call System.Environment.GetCommandLineArgs at any point in your application, which returns the same string array you’d get inside Main.

Please tell me that I did not just read the words single-threaded apartment! Isn’t that a legacy COM thing?

이미지
Yes, apartments are a COM mechanism. And like  previous  Win32-based  user interface frameworks (including Windows Forms), WPF requires the main thread to live in a single threaded apartment. This is mainly the case to enable seamless interoperability with non-WPF technologies (the topic of Chapter 19, “Interoperability with Non-WPF Technologies”). But even without the interoperability requirement, the STA model—in which developers don’t need to worry about correctly handling calls from arbitrary threads—is valuable for making programming with WPF easier. When an object is created on an STA thread, it can be called only on that same thread. WPF enforces that many of its APIs (on DispatcherObject-derived classes) are called from the correct thread by throwing an exception if the call comes from any other thread. That way, there’s no chance of accidentally calling such members from the wrong thread and only seeing intermittent failures (which can be incredibly hard to deb...

Commands in WPF.

 음 매우매우 기발하고 참신한 아이디어다. 행위의 추상화라... The Controls such as Button, CheckBox, and MenuItem have logic to interact with any command on your behalf. WPF’s built-in commands are exposed as static properties of five different classes: ApplicationCommands : Close, Copy, Cut, Delete, Find, Help, New, Open, Paste, Print, PrintPreview, Properties, Redo, Replace, Save, SaveAs, SelectAll, Stop, Undo, and more ComponentCommands  : MoveDown, MoveLeft, MoveRight, MoveUp, ScrollByLine, ScrollPageDown, ScrollPageLeft, ScrollPageRight, ScrollPageUp, SelectToEnd, SelectToHome, SelectToPageDown, SelectToPageUp, and more MediaCommands  : ChannelDown, ChannelUp, DecreaseVolume, FastForward, IncreaseVolume, MuteVolume, NextTrack, Pause, Play, PreviousTrack, Record, Rewind, Select, Stop, and more NavigationCommands  : BrowseBack, BrowseForward, BrowseHome, BrowseStop, Favorites, FirstPage, GoToPage, LastPage, NextPage, PreviousPage, Refresh, Search, Zoom, and more E...

Capturing the Mouse in WPF

WPF enables any UIElement to capture and release the mouse at any time. When an element captures the mouse, it receives all mouse events, even if the mouse pointer is not within its bounds. When an element releases the mouse, the event behavior returns to normal. Capture and release can be done with two functions defined on UIElements—CaptureMouse and ReleaseMouseCapture.

Handling Content Overflow

Clipping is default way and occurs before RenderTransforms are applied! Scrolling just wrap an element in a ScrollViewer control Scaling dynamically shrinking or enlarging content to “just fit” in a given space is more appropriate for several scenarios. Wrapping Trimming

Layout with Panels

이미지
Canvas StackPanel VirtualizingStackPanel which acts just like StackPanel but temporarily discards any items offscreen to optimize performance WrapPanel DockPanel which  is useful for arranging a top-level user interface in a Window or Page Grid. GridSplitter, SharedSizeGroup Although Grid looks like it can practically do it all, StackPanel and WrapPanel are better choices when dealing with an indeterminate number of child elements (typically as an items panel for an items control, described in Chapter 10. Also, a DockPanel with complicated subpanels is sometimes a better choice than a single Grid panel because the isolation provided by subpanels is more manageable when the user interface changes. With a single Grid, you might need to adjust RowSpan and ColumnSpan values to keep the docking illusion while rows and columns are added to the Grid. Primitive Panels : TabPanel, ToolBarPanel, ToolBarOverflowPanel,ToolBarTray, UniformGrid,...

Applying Transforms

All FrameworkElements have two properties of type Transform that can be used to apply such transforms: LayoutTransform, which is applied before the element is laid out RenderTransform (inherited from UIElement), which is applied after the layout process has finished (immediately before the element is rendered) There are the five built-in 2D transforms, all in the System.Windows.Media namespace: RotateTransform ScaleTransform SkewTransform TranslateTransform MatrixTransform

The main child layout properties

이미지
Be careful when writing code that uses ActualHeight and ActualWidth (or RenderSize)! Layout occurs asynchronously, so you can’t rely on the values of these properties at all times. It’s safe to access them only within an event handler for the LayoutUpdated event defined on UIElement. Margin and Padding have 1, 2 or 4 values(Left,Top,Right,Bottom). Visibility Visible : The element is rendered and participates in layout. Collapsed : The element is invisible and does not participate in layout. Hidden : The element is invisible yet still participates in layout.

WPF contains many powerful mechanisms that independently attempt to set the value of dependency properties.

이미지
Step 1: Determine the Base Value(in order from highest to lowest precedence) Local value  Parent template trigger Parent template Style triggers Template triggers Style setters Theme style triggers Theme style setters Property value inheritance  Default value Step 2: Evaluate Step 3: Apply Animations Step 4: Coerce Step 5: Validate SetCurrentValue WPF 4 adds a new method to DependencyObject called SetCurrentValue. It directly updates the current value of a property without changing its value source. (The value is still subject to coercion and validation.) This is meant for controls that set values in response to user interaction. For example, the RadioButton control modifies the value of the IsChecked property on other RadioButtons in the same group, based on user interaction. In prior versions of WPF, it sets a local value, which overrides all of the other value sources and can break things like data binding. In WPF 4, RadioButton has been change...

Dependency Properties.

Some of the ways that dependency properties add value on top of plain .NET properties: Change notification Property value inheritance Support for multiple providers

The core classes forming the foundation of WPF.

이미지

항상 궁금했던 opt in / out

opt to choose to take or not to take a particular course of action opt in (to sth) to choose to be part of a system or an agreement opt out (of sth) to choose not to take part in sth opt-out the act of choosing not to be involved in an aggrement After graduating she opted for a career in music Many workers opted to leave their jobs rather than take a pay cut. Employees may opt out of the company's pension plan

A few key scenarios which fulfil WCF Security

Intranet application Internet application Business-to-business application Anonymous application No security

Transfer Security Modes of WCF

이미지
The five transfer security modes are None Transport security : secure communication protocol for usually intranet Message security : simply encrypts the message itself Mixed : rarely need to use the Mixed mode Both :  The BasicHttpBinding supports username  client credentials for Message security only when configured for Mixed mode. This may be a source of  runtime  validation  errors,  since  the  BasicHttpMessageCredential Type enum  contains  the BasicHttpMessageCredentialType.UserName value.

Windows PowerShell security goals

이미지
Set-ExecutionPolicy 를 통해 실행 권한 설정을 하자. 아니면 Digital code signing을 하자.

A PowerShell Provider. 가장 중요한 개념이 아닐까 싶군.

A PowerShell provider, or PSProvider, is an adapter. It’s designed to take some kind of data storage and make it look like a disk drive. Provider 개념을 통해 대상에 대한 일관된 Interface를 제공하는 것이 큰 장점.

$_

This is the placeholder for the current value in the pipe line and must be in { }. 넹~.

Asynchronous Calls at client-side

WCF offers all of these options to clients. The WCF support is strictly a client-side facility, and in fact the service is unaware it is being invoked asynchronously. This means that intrinsically any service supports asynchronous calls, and that you can call the same service both synchronously and asynchronously. In addition, because all of the asynchronous invocation support happens on the client side regardless of the service, you can use any binding for the asynchronous invocation.

Per-call service with ConcurrencyMode.Multiple

An interesting observation here is that in the interest of throughput, it is a good idea to configure a per-call service with ConcurrencyMode.Multiple  — the instance itself will still be thread-safe (so you will not incur the synchronization liability), yet you will allow concurrent calls from the same client. For a service configured with ConcurrencyMode.Multipleto experience concurrent calls, the client must use multiple worker threads to access the same proxy instance . However, if the client threads rely on the auto-open feature of the proxy (that is, just invoking a method and having that call open the proxy if the proxy is not yet open) and call the proxy concurrently, then the calls will actually be serialized until the proxy is opened, and will be concurrent after that. If you want to dispatch concurrent calls regardless of the state of the proxy, the client needs to explicitly open the proxy (by calling the  Open()method) before issuing any calls on the worker thread...

Instances and Concurrent Access

Using the same proxy, a single client can issue multiple concurrent calls to a service. The client can use multiple threads to invoke calls on the service, or it can issue one-way calls in rapid succession on the same thread. In both of these cases, whether the calls from the same client are processed concurrently is the product of the service’s configured instancing mode , the service’s concurrency mode , and the configured delivery mode (that is, the transport session). The service’s i nstancing mode The service’s concurrency mode The configured delivery mode

In general, you should avoid ConcurrencyMode.Multiple in WCF

ConcurrencyMode.Single ConcurrencyMode.Reentrant ConcurrencyMode.Multiple 흠 실망...

Pipeline in PowerShell

오~ 놀랍다. Pipeline input ByValue Pipeline input ByPropertyName Custom properties Parenthetical commands Extracting the value from a single property import-XXX, select (-expand) 등등 잘 써보자.

Objects and Pipeline in PowerShell

Why PowerShell uses objects One of the reasons why PowerShell uses objects to represent data is that, well, you have to represent data somehow, right? PowerShell could have stored that data in a format like XML, or perhaps its creators could have decided to use plain-text tables. But they had some specific reasons why they didn’t take that route. The first reason is that Windows itself is an object-oriented operating system—or at least, most of the software that runs on Windows is object oriented. Choosing to structure data as a set of objects is easy, because most of the operating system lends itself to those structures. Another reason to use objects is because they ultimately make things easier on you and give you more power and flexibility. The pipeline: enabling power with less typing One of the reasons we like PowerShell so much is that it enables us to be more effective administrators without having to write complex scripts, like we used to have to do in VBScript. ...

Streaming transfer mode.

By  default,  when  the  client  and  the  service  exchange  messages,  these  messages are buffered on the receiving end and delivered only once the entire message has been received. This is true whether it is the client sending a message to the service or the service returning a message to the client. WCF enables the receiving side (be it the client or the service) to start processing the data in the message while the message is still being received by the channel. This type of processing is known as   streaming transfer mode . With large payloads, streaming provides improved throughput and responsiveness because neither the receiving nor the sending side is blocked while the message is being sent or received. Only the TCP, IPC, and basic HTTP bindings support streaming . With all of these bindings streaming is disabled by default, and the binding will buffer the message in its entirety even when a  Streamis used...

Events in WCF

이미지
(Ws)Http 바인딩에서는 잊자. The basic WCF callback mechanism does not indicate anything about the nature of the interaction between the client and the service. They may be equal peers in a commutative  interaction,  each  calling  and  receiving  calls  from  the  other. However,  the canonical use for duplex callbacks is with events. While events in WCF are nothing more than callback operations, by their very nature events usually imply a looser relationship between the publisher and the subscriber than the typical relationship between a client and a service.

Callbacks are also commonly referred to as duplex operations

Not all bindings support callback operations. Only bidirectional-capable bindings support callback operations. For example, because of its connectionless nature, HTTP cannot be used for callbacks, and therefore you cannot use callbacks over the  BasicHttpBinding or the WSHttpBinding. The only two commonly used bindings that offer callbacks are the  NetTcpBinding and the  NetNamedPipeBinding, because by their very nature, the TCP and the IPC protocols support duplex communication. To support callbacks over HTTP, WCF offers the WSDualHttpBinding, which actually sets up two WS channels: one for the calls from the client to the service and one for the calls from the service to the client. But the  NetTcpRelayBinding by and large deprecates the  WSDualHttpBinding in the vast majority of callback cases.

Bindings, Reliability, and Ordered Messages

이미지

WCF에서 Reliability가 메세지 전달을 보장하지는 않는다.

Message reliability does not guarantee message delivery. It provides only a guarantee that  if the message does not reach its destination, the sender will know about it.

PowerShell에서 파일에 저장된 값을 파라미터 값으로 쓰기

Get-EventLog Security -ComputerName (Get-Content l.txt) 아항~

Instance Management.

이미지
Per-Call Services It must be state-aware . The client has no way of calling the  Dispose()   method anyway. Per-Session Services The  BasicHttp Binding can never have a transport-level session. The WSHttpBinding without Message security and without reliable messaging will also not maintain a transport-level session.

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 은 좀 뜻밖이군.

Converting between types.

Casting Using the as operator Parsing. 문자열을 원하는 타입으로. Using System.Convert Using System.BitConverter. byte스트림을 원하는 값으로. Casting value type reference type Narrowing conversion 데이타 손실이 있을 수 있는 경우 is/as 사용해서 확인 후 Widening conversion 데이타 손실이 없는 있는 경우 상위 클래스로

CLR 관점에서는, Method의 Signature는 Method의 이름, Parameters로 구성된다. Return type은 아니다.

난 무식하다. ㅠㅠ

C# and Jon Skeet

너가 C#을 하는데, Jon Skeet을 모른다면 뭔가 문제가 있다. http://meta.stackoverflow.com/questions/1832/what-happens-when-jon-skeets-reputation-exceeds-the-limit-for-the-data-type-hol https://www.google.co.kr/search?q=jon+skeet+wiki&oq=Jon+Skeet&aqs=chrome.1.69i57j0j69i60j0l2.5194j0&sourceid=chrome&ie=UTF-8#newwindow=1&q=jon+skeet+chuck+norris http://codesqueeze.com/the-ultimate-top-25-chuck-norris-the-programmer-jokes/

현재 MS의 인증 프로그램(Certification program)

Solutions Associate level Designed to be the foundation for certifications in Microsoft proving technical skills. Solutions Expert level Expands on the knowledge of those at the Associate level and requires more rigor in the exams and knowledge tested. Candidates at this level should be able to build solutions using multiple technologies including cloud computing. Solutions Master level The top of the Microsoft certification program. Consists of certifications that require knowledge-based exams along with performance-based testing. Those who hold a Masters certification demand higher salaries.

.NET에서 제공되는 기본 Serialization 방법

XmlSerializer DataContractSerializer BinaryFormatter

LINQ to XML. 읽는 것은 모르겠는데, 쓰는 것은 확실히 편해보인다.

XML을 만들 때, XmlDocument 보단 더 편하다. var root = new XElement("Root", new List { new XElement("Child1"), new XElement("Child2"), new XElement("Child3") }, new XAttribute("Attr1", 10000), new XAttribute("Attr2", 20000), new XAttribute("Attr3", 30000)); root.Save("test.xml");

The Standard query operators.

All, Any, Average, Cast, Count, Distinct, GroupBy, Join, Max, Min, OrderBy, OrderByDescending, Select, SelectMany, Skip, SkipWhile, Sum, Take, TakeWhile, ThenBy, ThenByDescending, and Where. 그러하다.

XML in the .NET Framework

XmlReader A fast way of reading an XML file. You can move forward only through the file, and nothing is cached XmlWriter A fast way to create an XML file. Just as with the XmlReader, it’s forward only and noncached. XmlDocument Represents an in-memory XML document. It supports navigating and editing a document. XPathNavigator Helps with navigating through an XML document to find specific information. more  혹은  LINQ to XML

System.Transactions.TransactionScope 가 분산(Distributed) 트랜잭션도 처리할 수 있음.

로컬 트랜잭션만 자동으로 처리하는지 알았는데, 커넥션 객체가 두 개 이상 생기면, 분산 트랜잭션으로 바뀐다네. http://msdn.microsoft.com/en-us/library/ff649002.aspx http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope(v=vs.100).aspx

미처 몰랐던 System.IO.Path의 유용한 메서드

GetDirectoryName GetExtensions GetFileName GetPathRoot GetRandomFileName GetTempPath GetTempFileName http://msdn.microsoft.com/en-us/library/System.IO.Path(v=vs.100).aspx

Diagnostics in application.

Logging and Tracing Profiling application with StopWatch or Performance wizard Monitoring Performance Counters 아는 것이 많아질수록 어렵구나. ㅠㅠ

.PDB 파일

PDB 파일은 다음의 정보를 담고 있다. 소스 파일 이름과 줄번호 로컬 변수 이름 위의 두 정보는 디버깅시에 필요하다. 그리고 어셈블리 빌드시에 함께 만들어진 PDB 파일은 "Microsoft Symbol Server" 를 통해 디버거에게 보내질 수 있다. 단 이때 PDB파일에 담겨있는 Private 정보를 제거하려면 PDBCopy라는 프로그램을 이용해야 한다.

어셈블리를 바인딩하는 과정에 필요한 설정 파일

Publisher policy files : GAC Application configuration files  Machine configuration files 기타 주의사항 참조할 Private 어셈블리는 기본적으로 현재 실행 폴더나 하위 폴더에 있어야 한다. private 어셈블리의 위치는 "probing" 요소에서 상대 경로로 정할 수 있다. App.config 파일에 "codebase" 요소에서 지정된 위치에서 Public 어셈블리만 가져올 수 있다.

SecureString. 문자열을 해킹으로부터 지키자.

System.Security.SecureString 덤프나 페이지 파일을 통해서 원치 않는 문자열 정보가 유출될 수 있다. public static void ConvertToUnsecureString(SecureString securePassword) { IntPtr unmanagedString = IntPtr.Zero; try { unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword); Console.WriteLine(Marshal.PtrToStringUni(unmanagedString)); } finally { Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString); } }

Hashing is the process of taking a large set of data and mapping it to a smaller data set of fixed length.

그러하다. 참 깔끔한 정의다.

자주 쓰이는 정규식 패턴 검색. http://regexlib.com/

http://regexlib.com/ 굿~

Format 문자열의 정확한 문법. 차지하는 글자수를 정할 수 있는 옵션이 있는 줄은 미처 몰랐다.

A format item has the following syntax: { index [ , alignment ][  :   formatString ]  } Brackets denote optional elements. The opening and closing brackets are required. A format item has the following elements: index The zero-based index of the argument whose string representation is to be included at this position in the string. If the argument is  null , an empty string is included at this position in the string. alignment A signed integer that indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer). If  alignment  is omitted, the string representation of the corresponding argument is inserted in a field with no leading or trailing spaces. formatString A format string that specifies the format of the corresponding argument's result string. If  formatString  is omitted, the corresponding argument's parameterless  ToS...

MSDN 한글판의 문제점.

이제까지는 영문판만 봐서 미처 몰랐는데, 한글판은 번역이 안 된 경우만 있는 것이 아니고, 아예 일부 내용이 누락된 경우도 있나 보네. String.Format에 대한  영문판    한글판 Remark 섹션이 통채로 날아갔다. 헐... 아무리 생각해도 영어, 최소한 독해가 안 되면 개발자로 살아가기는 어려울 듯.

문자열 다룰 때 Globalization 고려해야 한다면 아래의 사항을 조심.

Make sure that all string comparisons use an explicit overload that takes a StringComparison object.  Use StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase when comparing strings in a culture-agnostic way. Use StringComparison.CurrentCulture when displaying text to the user. Make sure that all persisted text is persisted with the invariant culture. Make sure that you are not using String.Compareor CompareTofor equality testing. Implement IFormattablefor custom types that are displayed to the user to make sure that all culture settings are respected. Use the correct format strings when displaying numbers, dates, and times to the user. 

.NET에서 Excel 파일 읽기. 특히 구버전(97-2003)의 포맷일 경우.

NPOI  라이브러리 이용. Thanks to 안홍조 & 정세일 . CSV 포맷으로 올려서 읽는다. ODBC 드라이버를 설치해서 읽는다.  ODBC 연결 문자열 2003 이전 구포맷일 경우 상용컴포넌트 사용 ExpertXLS Excel Library for .NET ComponentOne 2007 이후 버전(Open XML Format) 일 경우 EPPlus , ClosedXml ,  NPOI  등등 매우 많은 오픈소스 프로젝트가 있다. Sql Server의  SQL Server Integration Services (혹은 DTS) 를 이용한다. 이 방법을 이용하려면, SSIS를 설치해서, DTS 패키지를 만든 후에, 이 DTS 패키지를 Job스케쥴러에 등록해서, Job을 실행시키면 된다. 단 SSIS가 설치된 컴퓨터에서 파일을 읽을 수 있어야 하고, 읽은 파일을 바로 DB의 테이블로 Export 시키기 위해서는 SQL Server의 계정이 sysadmin 서버역할이 부여되야 한다. 서버에 Excel을 직접 설치해서 COM을 이용해 읽는 것은 안 된다. Excel 프로그램이 무인실행을 위해 만들어진 프로그램이 아니기 때문에, 읽은 파일을 못 닫거나, 메모리 누수와 같은 문제가 발생할 수 있다. 구버전 파일의 경우 현실적으로 StackOverflow 에서처럼 ODBC 드라이버가 대세이지만,  ODBC를 이용해 읽는 방법은 32/64bit OS에 따라 다른 드라이버 를 설치해야 하고, ODBC 드라이버에서 각 컬럼의 데이타 타입을 유추할 때, 첫 몇 줄을 이용해서 판단하는데 조금 문제가 있다. 특히 셀 값을 텍스트로 입력하지 않으면(셀값의 앞에 apostrophe '를 붙히지 않으면) 포맷은 숫자지만 실제로는 텍스트 인데, 읽으면 숫자로 인식해버린다. 예를 들어 00033223 가 33223으로 읽히거나,  매우 긴 숫자면 Single/Double 타입...

IDisposable

Finalizer는 GC가 호출하는 거고, Dispose는 니가 직접 호출하는 거다. public class DisposeExample { // A class that implements IDisposable. // By implementing IDisposable, you are announcing that // instances of this type allocate scarce resources. public class MyResource: IDisposable { // Pointer to an external unmanaged resource. private IntPtr handle; // Other managed resource this class uses. private Component component = new Component(); // Track whether Dispose has been called. private bool disposed = false; // The class constructor. public MyResource(IntPtr handle) { this.handle = handle; } // Implement IDisposable. // Do not make this method virtual. // A derived class should not be able to override this method. public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // T...