2014의 게시물 표시

Extensions for VS

http://stackoverflow.com/questions/2757357/visual-studio-2010-recommended-extensions

Library for Office Word

Spire.Doc  :  도움말 It has many restrictions. It's not totally free. It's evil.

.NET 코멘트 관리 자동화 프로그램들

GhostDoc  : 유명한 코멘트 생성 헬퍼 http://www.atomineerutils.com/  : 자동 코멘트 생성 등등 VSdocman : 도움말 생성 프로그램 Doxygen  : 도움말 생성 프로그램(프리)

Content컨트롤에 DataTemplate 붙혔을때, 템플릿의 컨트롤 찾는 방법.

Content컨트롤에 템플릿을 로드시키면 실제로는 Content의 자식인 ContentPresenter에 할당이 된다. 따라서 먼저 VisualTreeHelper.GetChild(컨텐트, 0) 해서 찾자 ApplyTemplate() 해줘야 반영이 되는 경우가 있다. 컨텐트컨트롤.ContentTemplate.FindName("이름", 찾은 contentPresenter) 해서 찾자.

Creating EventSetter in code.

Setters.Add(new EventSetter(이벤트, 이벤트 핸들러); 이벤트핸들러는 new ......EVentHandler(메서드); 이렇게

THREADING AND COM

The Component Object Model (COM) was Microsoft’s previous technology for building components. Many organizations have legacy COM objects that they need to use in their applications. A goal of COM was to ensure that different technologies could use one another’s components, and so a COM object written in VB 6 could be used from COM code written in C++—or at least that was the theory. The problem was that VB was not multithread aware and so internally made assumptions about which thread it was running on. C++ code could quite happily be multithreaded, and so by calling a VB component directly from a C++ one could potentially cause spectacular crashes. Therefore, thread-aware and thread-unaware code needed to be kept separate, and this was achieved by the notion of apartments. Thread-unaware components lived in Single Threaded Apartments (STAs), which would ensure they were always called on the same thread. Other components could elect to live in the Multithreaded Apartment (MTA ) or an...

The keyword of Volatile in C#

http://msdn.microsoft.com/en-us/library/x13ttww7.aspx http://www.codeproject.com/Articles/31283/Volatile-fields-in-NET-A-look-inside 여러 스레드에 의해서 접근되는 경우에 사용. 그 이유는 JIT컴파일러가 옵티마이즈를 위해, 해당 필드를 cpu 캐시에 올려놓을 수 있기 때문이다.

Famous MVVM frameworks

MVVM Light Toolkit ( http://mvvmlight.codeplex.com / ): A popular framework  supporting both WPF and Silverlight (and now with Windows 8 Store apps as well),  written by Laurent Bugnion. Simple MVVM Toolkit ( http://simplemvvmtoolkit.codeplex.com/ ): Works  with WPF, Silverlight, and Windows Phone 7.x. Claims to be more feature rich than  MVVM Light Toolkit. Caliburn Micro ( https://github.com/Caliburn-Micro/Caliburn.Micro / ): A feature rich  framework, closer to Prism in functionality (see next section) that works with WPF,  Silverlight, Windows Phone 7.x, and the n ew  Windows 8 Store style applications.

x:Static Markup Extension

http://msdn.microsoft.com//library/ms742135(v=vs.110).aspx The code entity that is referenced must be one of the following: A constant A static property A field An enumeration value 를 xaml에서 참조할 수 있다. eg) CommandParameter="{x:Static enum:RecordCommandEnum.ImageCompare}"

간단 MVVM 이해

이미지

xaml에서 Enum 사용하기.

StaticExtension 이용해서 참조.

About Box for WinForm

윈폼용 About Box. 굿~
Reactive Extension 설치 신기하다...

getMatchedCSSRules and IE

extract all IHTMLStyleSheetRules of document. filter those by interesting style value. test whether a element is able to be applied to rule by msMatchesSelector method, which is invoked with arguments;selectorText of rule and the element. CSSUtilities  seems not to support IE10+.

Reflection with IDispatch-based COM objects

Reflection with IDispatch-based COM objects #region Using Directives using System; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Permissions; #endregion namespace COM_Test { /// <summary> /// Provides helper methods for working with COM IDispatch objects that have a registered type library. /// </summary> public static class DispatchUtility { #region Private Constants private const int S_OK = 0; //From WinError.h private const int LOCALE_SYSTEM_DEFAULT = 2 << 10; //From WinNT.h == 2048 == 0x800 #endregion #region Public Methods /// <summary> /// Gets whether the specified object implements IDispatch. /// </summary> /// <param name="obj">An object to check.</param> /// <returns>True if the object implements IDispatch.  False otherwise.</returns> public static bool ImplementsIDispatch(object obj) { bool result = obj is ID...

Best C# Practices.

http://www.codeproject.com/Articles/593751/Code-Review-Checklist-and-Guidelines-for-Csharp-De

IE automation. dialog watcher

http://msdn.microsoft.com/en-us/magazine/gg309183.aspx public   class   Form1  :  Form   {     [ DllImport ( "user32.dll" ,  EntryPoint = "FindWindow" ,  CharSet = CharSet . Auto )]      static   extern  IntPtr  FindWindow ( string   lpClassName ,  string   lpWindowName );     [ DllImport ( "user32.dll" ,  EntryPoint = "FindWindowEx" ,  CharSet = CharSet . Auto )]      static   extern  IntPtr  FindWindowEx (IntPtr  hwndParent , IntPtr  hwndChildAfter ,  string   lpszClass ,  string   lpszWindow );     [ DllImport ( "user32.dll" ,  EntryPoint = "PostMessage" ,  CharSet = CharSet . Auto )]      static   extern   bool   PostMessage1 (IntPtr  hWnd ,  uint   Msg ,  int   wParam ,  int ...

.NET 메모리 분석

http://www.codeproject.com/Articles/176031/Out-of-Memory-Exception-A-simple-string-Split-can

무료 압축, 이미지 프로그램

http://www.nomacs.org/ http://www.7-zip.org/

WPF BackgroundWorker vs. Dispatcher

http://stackoverflow.com/questions/3762576/wpf-backgroundworker-vs-dispatcher

Woker thread에서 Exception 발생하면 죽는다.

http://www.codeproject.com/Articles/610876/HandlingplusExceptionsplusinplusPluginsplusHostedp Exceptions in Managed Threads 죽는다. 절대로 반드시 죽는다. .NET 2.0 이전의 처리 방식으로 돌아가려면 < runtime > < legacyUnhandled Exception Policy enabled =" 1" / > < / runtime >

ImageFormat과 관련있는 확장자 알아보기

http://stackoverflow.com/a/14159385

AddressAccessDeniedException 발생하면

netsh http add urlacl url=http://+:80/ user=users http://blogs.msdn.com/b/amitlale/archive/2007/01/29/addressaccessdeniedexception-cause-and-solution.aspx

System.Windows.Input.ICommand 구현

         public   bool   CanExecute ( object   parameter )         {              return   _imageData . ImagePath   !=   null ;         }          public   event   EventHandler   CanExecuteChanged         {              add  {  CommandManager . RequerySuggested   +=   value ; }              remove  {  CommandManager . RequerySuggested   -=   value ; }         } 잘 이해는 안 된다... ㅠㅠ. WPF가 바인딩된 모든 Command들의 실행 가능 상태가 바뀔 때로 예상되면, 실행하는 CommandManager.RequerySuggestedstatic event 에등록....

Blendability : Degign 모드에 DataContext 설정

뷰의 xaml 코드에 다음을 추가. < Window  x : Class = "WpfApplication1.Window1"          xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"          xmlns : x = "http://schemas.microsoft.com/winfx/2006/xaml"           xmlns : d = "http://schemas.microsoft.com/expression/blend/2008"          xmlns : mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"          mc : Ignorable = "d"          d : DataContext ="{ d : DesignInstance  Type = local : ImageData ,  IsDesignTimeCreatable = True } "          xmlns : local = "clr-namespace:WpfApplication1"          Title = "Window1"  Height = "452"  Width = "624.972" > 그리...

Why MVVM?

The event handler is part of the "code behind" where the UI is declared, typically a window or a user control. This makes it difficult to call from other objects that may want to invoke the same logic. The aforementioned button may disappear and be replaced by (say) a menu item. This would require the event hooking code to potentially change. What if we wanted both a button and a menu item? An action may not be allowed at a certain state – the button (or whatever) needs to be disabled or enabled at the right time. This adds management overhead to the developer – the need to track state and change it for all UI elements that invoke the same functionality. An event handler is just a method – there's no easy way to pick it up and save it somewhere, such as for undo/redo purposes. It's difficult to test application logic without using actual user interface. These, and other, more subtle issues, make working with event handlers less than ideal, especially when app...

Expression tree vs Reflection

http://stackoverflow.com/questions/4803272/in-c-is-expression-api-better-than-reflection

WebBrowser Control Wrapper

http://www.codeproject.com/Articles/555302/A-better-WPF-Browser-Control-IE-Wrapper

dynamic object serializing

http://www.codeproject.com/Articles/62839/Adventures-with-C-dynamic-ExpandoObject-Elasti http://stackoverflow.com/questions/3055461/dynamic-object-serialization http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=vs.100).aspx

Visual Studio execution error - can't find module.

1. Reinstall Visual Studio 2. If it's not working, reinstall the .NET Framework.

COM Interop에서 dynamic의 적절한 사용

From C# 4.0, variant types are instead mapped to dynamic (if Embed Interop Types is enabled; more on this soon), allowing you to replace the last two lines with this: excel.Cells [1, 1].Font.FontStyle = "Bold"; The disadvantage of working in this way is that you lose auto-completion, so you must know that a property called Font happens to exist. For this reason, it’s usually easier to dynamically assign the result to its known interop type: Excel.Range range = excel.Cells [1, 1]; range.Font.FontStyle = "Bold"; As you can see, this saves only five characters over the old-fashioned approach!

(IDispatch) COM 객체의 타입명 찾기.

Microsoft.VisualBasic.Information.TypeName(XXX) 개같은 COM Interop

Set rendering mode to ie9 when using webbrowser control.

http://stackoverflow.com/a/6770294

Why The Command?

이미지

Disabling a control to have built-in command support

Ideally, the control will provide a property that allows you to gracefully switch off the command support. This ensures that the control will remove the feature and adjust itself consistently. For example, the TextBox control provides an IsUndoEnabled property that you can set to false to prevent the Undo feature. (If IsUndoEnabled is true, the Ctrl+Z keystroke triggers it.) If that fails, you can add a new binding for the command you want to disable. This binding can then supply a new CanExecute event handler that always responds false. The final option is to remove the input that triggers the command by using the InputBindings collections. For example, you could disable the Ctrl+C keystroke that triggers the Copy command in a TextBox by using code like this: KeyBinding keyBinding = new KeyBinding(ApplicationCommands.NotACommand, Key.C, ModifierKeys.Control); txt.InputBindings.Add(keyBinding);

FocusManager

This example has an interesting detail. The Cut, Copy, and Paste commands are handled by the text box that has focus. However, the command is triggered by the button in the toolbar, which is a completely separate element. In this example, this process works seamlessly because the button is placed in a toolbar, and the ToolBar class includes some built-in magic that dynamically sets the CommandTarget property of its children to the control that currently has focus. (Technically, the ToolBar looks at the parent, which is the window, and finds the most recently focused control in that context, which is the text box. The ToolBar has a separate focus scope, and in that context, the button is focused.) If you place your buttons in a different container (other than a ToolBar or Menu), you won’t have this benefit. That means your buttons won’t work unless you set the CommandTarget property manually. To do so, you must use a binding expression that names the target element. For example, if the...

MVVM Light 설치

PM> Install-Package MvvmLight

Data Conversion in Binding

StringFormat 속성 .NET 기본 포맷 문자열 사용 입력값이 여러 개면 MultiBinding 을 사용. Value Converter IValueConverter  나  IMultiValueConverter  를 구현한다. 그리고 Attribute에 소스와 타겥 타입을 지정하고, XAML에 리소스에 포함해서 사용. 파워풀하네~.

Resource를 위한 별도의 Assembly를 만든다면 URI는 절대경로를 사용해라.

런타임에 다른 Application에서 사용되므로, 상대경로로 정의된 파일을 찾지 못한다. Resource assembly는 다음처럼 만들어라. 클래스라이브러리 프로젝트라면 assemblyinfo.cs 에 어트리뷰트를 추가 하고 [ assembly : ThemeInfo ( ResourceDictionaryLocation . None , //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation . SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] 용도별로 따로 Resource Dictionary를 만들어서, /Themes/generic.xaml 에서 파일을 절대경로로 포함시켜서 머지하고, 더미클래스를 하나 정의하고, 다른 어셈블리에서 참조될 수 있도록,  ComponentResourceKey 를 이용해 키를 부여한다. DynamicResource 를 이용해 필요한 리소스를 참조해서 이용한다.

Pack URIs in WPF

WPF에서는 파일 위치를 정의하기 위해 uniform resource identifiers(URI)를  사용한다. Specifying the user interface (UI) to show when an application first starts. Loading images. Navigating to pages. Loading non-executable data files. 그리고 URI는 다양한 위치를 정의할 수 있다. The current assembly. A referenced assembly. A location relative to an assembly. The application's site of origin. 더 자세한 설명은 생략한다. 복잡하다.

StaticResource vs DynamicResource

At this point, you’re probably wondering what the difference is between a static and dynamic resource. The difference is that a static resource grabs the object from the resources collection once . Depending on the type of object (and the way it’s used), any changes you make to that object may be noticed right away. However, the dynamic resource looks the object up in the resources collection every time it’s needed . That means you could place an entirely new object under the same key, and the dynamic resource would pick up your change. As a general guideline, use dynamic properties only when you have these conditions: Your resource has properties that depend on system settings (such as the current Windows colors or fonts). You plan to replace your resource objects programmatically.

Bind to objects that aren't Elements

How to specify the source : Source  : An existing object. To refer to an existing object, use the StaticResource Markup Extension RelativeSource : Gets or sets the binding source by specifying its location relative to the position of the binding target. RelativeSource MarkupExtension DataContext : The binding source for multiple elements is defined once.

The Binding Class

Binding  원다풀~~~. 윈도우 UI 프로그래밍은 윈폼/WPF 모두 바인딩을 얼마나 잘  쓰느냐가 관건이다. 생산성 떨어지는 날코딩은 이제 그만하자. 참고로 일단 소스-타겥이 바인딩으로 연결된 후에, 타겥의 바인딩된 프라퍼티를 직접 설정하면 바인딩이 해제된다. 흔히 하는 실수. 일단 바인딩이 이루어졌으면 타겥의 프라퍼티는 항상 소스를 통해서 업데이트 해야 한다. 바인딩을 지우거나 바인딩 정보를 얻으려면  BindingOperations 을 이용한다. ClearBinding GetBinding 타겥은 항상 소스가 변하면 바로 업데이트 되지만(단 INotifyPropertyChanged  를 구현한 경우에만), 소스는 바로 업데이트 안 된다. UpdateSourceTrigger  ; PropertyChanged, LostFocus, Explicit, Default

Resources in WPF

StreamResourceInfo  가 아니더라도, Image의 Source 프라퍼티는 리소스 경로를 해석할 수 있다. 리소스 경로는 상대 경로를 사용하거나, 절대 경로를 사용한다. pack://application:,,,/[ AssemblyName ;component/] ResourceName 그리고  Content file 을 이용해 파일 자체를 포함시켜도 리소스의 경우와 같은 문법을 사용한다.

Button의 재밌는 두 속성

IsCancel When IsCancel is true, this button is designated as the cancel button for a window. If you press the Esc key while positioned anywhere on the current window, this button is triggered. IsDefault When IsDefault is true, this button is designated as the default button (also known as the accept button). Its behavior depends on your current location in the window. If you’re positioned on a non-Button control (such as a TextBox, RadioButton, CheckBox, and so on), the default button is given a blue shading, almost as though it has focus. If you press Enter, this button is triggered. However, if you’re positioned on another Button control, the current button gets the blue shading, and pressing Enter triggers that button, not the default button.

The hierarchy of content controls

이미지

How can you fix WPF’s small-text display problem?

So how can you fix WPF’s small-text display problem? The best solution is to scale up your text (on a 96 dpi monitor, the effect should disappear at a text size of about 15 device-independent units) or use a highdpi monitor that has enough resolution to show sharp text at any size. But because these options often aren’t practical, WPF also has the ability to selectively use GDI-like text rendering. To use GDI-style text rendering, you add the extOptions.TextFormattingMode attached property to a text-displaying element such as the TextBlock or Label, and set it to Display (rather than the standard value, Ideal). Here’s an example: <textblock fontsize="12" margin="5"> This is a Test. Ideal text is blurry at small sizes. </textblock> It’s important to remember that the TextFormattingMode property is a solution for small text only. If you use it on larger text (text above 15 points), the text will not be as clear, the spacing will not be as even, and the ...

The EventArgs classes for input events

이미지

항상 Loaded 이벤트에서 추가적인 초기화 작업을 수행하자.

You can also use the window constructor to perform your initialization (just add your code immediately after the InitializeComponent() call). However, it’s always better to use the Loaded event. That’s because if an exception occurs in the constructor of the Window, it’s thrown while the XAML parser is parsing the page. As a result, your  exception is wrapped in an unhelpful XamlParseException object (with the original exception in the InnerException property).

IoC(혹은 DI) Container 성능비교

.NET에서 사용되는 여러 IoC 컨테이너 성능비교 추천 Injector : Simple Injector

데이타로우로 C# 객체 생성하기

AutoMapper http://www.geekytidbits.com/automapper-with-datatables/ http://stackoverflow.com/questions/16222313/how-to-use-automapper-to-map-a-datarow-to-an-object-in-a-wcf-service DataRow로부터 POCO를 생성할 때(Projection), AutoMapper를 이용하자. 깔끔하다.

DataRow의 컬럼 값을 Generic(strongly-typed)한 방법으로 읽기

잘 몰랐을 때는 ToString()을 통해 문자열로 바꿔서, 다시 원하는 타입으로 파싱을 했는데 솔직히 좀 구리다. DataRowExtensions.Field Method  를 이용해야 한다. 타입 컨버전을 하지 않기 때문에 빠르다. 게다가 Nullable 타입도 지원한다.  http://stackoverflow.com/a/4593758 DataTable dt = new DataTable(); var someValue = dt.Rows[0].Field ("aaa");

WPF Events usually fall into one of five categories

Lifetime events : These events occur when the element is initialized, loaded, or unloaded. Mouse events : These events are the result of mouse actions. Keyboard events : These events are the result of keyboard actions (such as key presses). Stylus events : These events are the result of using the pen-like stylus, which takes the place of a mouse on a Tablet PC. Multitouch events : These events are the result of touching down with one or more fingers on a multitouch screen. They’re supported only in Windows 7 and Windows 8.