Questions

View QAs in Chinese

C#

Extract key information from this great explanation

  • #if DEBUG: The code in here won’t even reach the IL on release.
  • [Conditional("DEBUG")]: This code will reach the IL, however calls to the method will be omitted unless DEBUG is set when the caller is compiled.

Common Best Practice

  • Use #if DEBUG for different variable assignment.
  • Use [Conditional("DEBUG")] for method invocation.

  1. Right click on the project and select Properties
  2. Go to the Debug Tab
  3. Click on the radio button for Start External Program. Point it to the devenv.exe binary. On my machine it’s located at C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe On a non x64 machine though you can remove the “ (x86)” portion.
  4. Then set the command line arguments to /rootsuffix Exp

Link

Need to reference Microsoft.CSharp

no stable extension so far, only available one is https://github.com/lukesdm/image-comments without maintenance for years

No, many famous extension didn’t sign itself.

ildasm.exe xxx.dll /out:xxx.il
ilasm.exe xxx.il /dll /key=xxx.snk /output=xxx-signed.dll

protected internal means protected OR internal. In order to make it protected AND internal, mark parent as internal

It’s impossible to set value through dynamic, instead, use reflection with BindingFlags.Instance | BindingFlags.NonPublic

Only way is use agent.

Differentiate Select-All and Single-Select by event source/args.

Right click file in solution, Annotate

  1. use variable to lock
  2. use Loaded event to wire SelectionChanged event.

  • Shift+Esc: Jump Between
  • Ctrl+Alt+[-/+]: Navigate between definition window
  • [Shift+]F8: navigate between multiple results

No comparison found, however, obviously AppDomain should be much faster than process which not involving a lot of system resource allocation.

In a word, linq was not designed to be asynced.

Lesson learned:

  1. Don’t use async/await in .Net 4.0.
  2. Use Task.Run to replace the CPU intensive code.
  3. Need to manually fire PropertyChanged event for ViewModel.

It marks with [DataContract], maybe mark field with [DataMember] can fix this(not test).

Because the event, change it to:

[field:NonSerializable]
public event ChangedEventHandler PropertyChanged;

Use AssemblyBuilder

No, because it’s Attribute which only read by some program runtime.

Task.Run is available since .Net 4.5 and this error would disappear after switched target to 4.5

  • AssemblyVersion is used for assembly reference.
  • FileVersion is used for mark which build the assembly produced.
  • ProductVersion is used for marketing, not used in program. Note: aka AssemblyInformationalVersion

eg, version of mscorlib 2.0.0.0

  • AssemblyVersion: 2.0.0.0
  • FileVersion: 2.0.50727.3521
  • ProductVersion: 2.0.50727.3521

  1. still cannot achieved by using code analysis
  2. use .Net Architecture Checker

Scenario is when try to load two different version of assemblies.(same code with different Assembly Version)

It’s limitation to Xaml generator. Workaround:

  1. put <AssemblyVersion> in .csproj file.
  2. use build parameter.

Ignore it, as it’s internal mechanism to try to load it.

  • LoadFrom, default action when .Net load assembly, load only once for same identity even in two location with different meta data.
  • LoadFile, load exactly what was requested, and would not load dependency.

Use following code instead of Task.Run, Source

More

Example code which raises the error:

public Point Origin { get; set; }

Origin.X = 10; // fails with CS1612
More

Scenario Description: for some reason we don’t want to modify the main configure file which name is xxx.exe.config, so we store configures in another file ConfigurationFile.

More

“This behavior is intentional.”

More

Solution: Wrapping in lambda function.

Link

The unit test hangs at following statement which is working well in real life WPF program.

More

In my application TouchAssistant I want it disappear after few seconds if no user interaction, however, after called DragMove(), there is no chance for me to listen to extra events to know if user still interacted with the program.

More

The goal I want to achieve is send keystroke to another application, which is the core function of my new open source application TouchAssistant. And I want the keystroke can be customized easily by configuration from user interaction.

More

I'm facing the same situation like this link.

More

My code generator requires to generate code with right indentation, so I need to prefix spaces for each line of a string. After google the world, there isn’t a out-of-box solution for me to use, finally I came up with my own solution:

internal static string Indent(this string content, int level = 1) =>
    string.Join(Environment.NewLine, content
        .Split(new[] { "\r\n" }, StringSplitOptions.None)
        .Select(_ => $"{(_ == string.Empty ? string.Empty : new string(' ', level * 4))}{_}")
        .ToArray());

Usage like this:

var result = str.Indent();

Scenario: I have made some utilities to generate C# code, however, I just utilize literal string with string.format, which is not good enough after Roslyn come out. So I tried to generate semantic code using Roslyn.

More

Git

One-liner:

git rev-list --objects --all | grep "$(git verify-pack -v .git/objects/pack/*.idx | sort -k 3 -n | tail -10 | awk '{print$1}')"

Link

Directly merge them, you may want use filter-branch if subdirectory needed.

use filter-branch --tree-filter

Add following pattern:

.*
!/.gitignore

Link

  1. .gitattributes file in root folder of your git project
    *.docx diff=pandoc
    
  2. .gitconfig file in your home folder
    [diff "pandoc"]
     textconv=pandoc --to=markdown
     prompt = false
    

Link

Root cause is same name of branch and tag appears, usually we remove the conflicting tag to avoid the confliction.

Not possible, because reflog is local only.

No way, only to protect it.

git diff commit[..commit] >xxx.patch

Not supported in gitlab, github supported via API.

git push origin :branchname

git push --follow-tags

file://///.....

[[_TOC_]], NOTE: preview mode not work.

git log --all -- FILEPATH(wildcard allowed)

No Answer

The scenario of this question is because some company open source its project without sharing the whole history, so it keeps two different history copy.

No answer, however, without folder tracking merge a old branch to another branch which done rename a folder may not complete automatically.

git rev-list --max-parents=0 HEAD

git revert

git reset

However, if the repository don’t have the first commit, you may want rm -rf .git && git init

Git are case-sensitive, while Windows is case-insensitive.

Then a very strange situation happened when directory abc and Abc both exist in git repository. In *nix you may find they are two directory while in Windows, you will find only Abc directory exists.

Due to the character of git, security vulnerability was found and fixed in 2.2.1.

git symbolic-ref HEAD refs/heads/branchname

git log -S <string> path/to/file(wildcard supported)
git log -G <regex> path/to/file(wildcard supported)

Linux

use ||

No simple solution, one way is to use || ignore all error

cAdvisor has very basic function, while influxdb is only a database. They can be used in combination, other keyword is docker-monitor

for D in *; do [ -d "${D}"] && my_command; done

  • ps aux --sort rss Link
  • free -m

Just restart

More

# If ~./inputrc doesn't exist yet, first include the original /etc/inputrc so we don't override it
if [ ! -a ~/.inputrc ]; then echo "\$include /etc/inputrc" > ~/.inputrc; fi
# Add option to ~/.inputrc to enable case-insensitive tab completion
echo "set completion-ignore-case On" >> ~/.inputrc

Link

  1. df to roughly find largest mount
  2. du -m --max-depth 1 | sort -rn | head -11 to find TOP 10 by size directories

Hint: use -h for human readable size format

date -r <filename>

Vim

Put following in vimrc

autocmd FileType markdown setlocal suffixesadd=.md,.markdown

Due to bug of Python 2.7.11, workaround:

  1. Install other version.
  2. after install execute following command (of course, need admin privilege). refer to Link
    reg copy HKLM\SOFTWARE\Python\PythonCore\2.7 HKLM\SOFTWARE\Python\PythonCore\2.7-32 /s /reg:32
    reg copy HKLM\SOFTWARE\Python\PythonCore\2.7 HKLM\SOFTWARE\Python\PythonCore\2.7-32 /s /reg:64
    

Use ge

The non-greedy version of * is \{-}. So, simply replace .* with .\{-

Link


* Convert bold: %s/\*\(.*\)\*/**\1**/g
* Convert named link: %s/\[\[\(.\{-}\)|\(.\{-}\)\]\]/[\2](\1)/g
* Convert link: %s/\[\[\(.\{-}\)\]\]/<\1>/g
* Title: 
  * First: %s/= \(.*\) =/# \1/g
  * May multiple: %s/=\(.*\)=/#\1/g
* Picture: %s/{{\(.\{-}\)}}/![](\1)/g
* Fenced code start: %s/{{{class="brush:\(.*\)"/```\1/g
* Fenced code end: %s/}}}/```/g
* Manual change # ordered list

1z=

Add following lines to vimrc:

if has('win32') || has('win64')
  set runtimepath=$HOME/.vim,$VIM/vimfiles,$VIMRUNTIME,$VIM/vimfiles/after,$HOME/.vim/after
endif

Link

  1. store operation in macro a
  2. [OPTIONAL] set nomore to avoid interruption during processing
  3. :bufdo execute "norma! @a" | update

~ in visual mode

  1. follow guide
  2. rename/remove /bin/vim from git bash which is not supported.

To count the number of matches of a pattern, use the substitute command with the n flag. The following shows the number of times that pattern matches text in the current buffer:

:%s/pattern//gn
More

&&, tip: help expr

vim -, eg: ls -la | vim -

  • ZZ save and exit
  • ZQ exit without save

^w followed by capital H,J,K or L will move the current window to the far left,bottom,top or right respectively like normal cursor navigation. Link

Misc

Could try ejs

Markdown not support it and so did some famous enhancement of original markdown, use following workaround:

  1. Use <BR /> or directly HTML code.
  2. Consider re-organize content to get rid of multi-line content.

Github use linguist as Parser.

Set in _config.yml

marked:
  breaks: false

Link

  1. eCLR.dll is compiled as managed CPP with lots of unsafe compiler option.
  2. the program is generated under project folder with .exe extension.
  3. eCLR.dll start process /eCLR/CIL-Compiler to compile from project to binary using method named LinkImage. (with uncertainty)
  4. Execute /eCLR/CIL-Compiler/____.exe ___/res/___.exe would generate ___.img.

npm prune

OneNote -> Review -> Language -> Set Spell Checker -> proper language

Sadly, no convenience way.

No such command line support, however, we can simply overwrite the setting file.

not dim means no secure desktop launched, it’s highly risky that already a malware on your PC.

Extension wasavi

Only way is to use a tool.

dsquery user -name Ja* Link

Windows

Execute following script with admin privilege.

assoc .jar=jarfile
ftype jarfile="C:\DevTools\jrex86\bin\javaw.exe" -jar "%%1" %%*

Link

Start with 2.7.9, pip already in python default installation package. To use it, just type python -m pip install {something}

put following script at the beginning of the batch file.

More

wmic path win32_networkadapter where NetConnectionID="Wireless Network Connection" call disable
wmic path win32_networkadapter where NetConnectionID="Wireless Network Connection" call enable

Unity

  1. I add an empty game object. I attach my new script.
    public void NextLevelButton(string levelName)
    {
        SceneManager.LoadScene(levelName);
    }
    
  2. I associate this game object with my new script to the Button(in the inspector) by: Clicking the +(plus) button to add a callback from an object->script->method.

Link

Detail can be found in editor.log located under C:\Users\xxx\AppData\Local\Unity\Editor\Editor.log Identified as a bug in community forum. Workaround is restart.

Found it may because last VS start failed and not close properly. Kill it in task manager first and try again.

get Renderer and change its material.color when OnMouseEnter/Over/Exit event Refer to http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseEnter.html

Edit -> Project Settings -> Editor. Set Version Control to meta files. Set Asset Serialization to force text.

Link

And download https://raw.githubusercontent.com/github/gitignore/master/Unity.gitignore

To add a level to the build settings use the menu File->Build Settings…

Link

Didn’t find why, however, set location at Start() workaround this issue, maybe it’s a bug.

Need Box Collider to detect this type of event.

Just use the type of that script as a field, and bind with the gameobject which has this type of script as component.

[GameObject].SetActive(false); another way is to disable renderer of that object.

Use animation. Don’t use code.

Drag and drop the model source file into the animation preview window. 

Link

Some things you can add by clicking on the prefab and adding items using the Component menu. For more involved changes, drag the prefab into the scene, make whatever changes are necessary (ignore the message about breaking the prefab link), and when done, select Apply Changes to Prefab from the GameObject menu. Then delete the prefab from the scene.

Link

  • use shader to calculate glow shadow (very complex)
  • visible/invisible or change color of a substrate/glow layer

Add image inside panel, change its anchor to left (hold shift key), change scale programmatically

  1. Use iTween
  2. Set use
    startPoint = CrewControl.transform.position;
    startTime = Time.time;
    endPoint = this.transform.position;
    

    Update use

    if (Time.time - startTime < duration)
    {
        CrewControl.transform.position = Vector3.Lerp(startPoint, endPoint, (Time.time - startTime) / duration);
    }
    

No way, do it in an image processing software.

So far as I know, no way.

Yes, only C# 4.0 supported.