11월, 2013의 게시물 표시

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.