Showing posts with label CSharp. Show all posts
Showing posts with label CSharp. Show all posts

Quick Fix: You can't debug the Silverlight application because the Silverlight Developer Runtime is missing

Tuesday, October 13, 2015
Problem
You've fired up the shiny new Visual Studio 2015 (or an older version) to debug a Silverlight 5 application and you get an error: "You need to install the latest Silverlight developer run-time before opening Silverlight project". And in matters requiring a blog post, the go.microsoft.com link provided doesn't go anywhere.
Solution
Microsoft, intelligently, gave up on Silverlight but there are still many projects that require it. My day job is Lync development and I needed this to troubleshoot a Lync CWE. All variations of the run-time are still available, but due to a security issue, they were moved to an obscure place... a security bulletin!
What you want is KB3162593 (updated to June 2016 patch), select Silverlight_Developer after clicking Download. Click the install link and you'll see Silverlight_Developer_Runtime.exe as an option. Be sure to uninstall Silverlight first, or you'll get an error. The 64-bit variant is there as well, along with the Version 5.0 SDK and others.
Woo Hoo! Time to party like it's 2011!
And in case you're looking for the Toolkit, it's still at its old CodePlex link.

HOWTO: Get the conditional compile symbols defined in the project for a source file (ITextView) in a Visual Studio Extension

Monday, August 31, 2015
One of the things I ran into when parsing with Roslyn in Stay Frosty was that #if / #endif blocks were treated as strictly in the parser as they are in Visual Studio (well, that should be obvious, it's the parser used by VS, isn't it?). That meant code that was riddled with preprocessor rules wasn't being parsed properly because it didn't know what I had defined.
Fortunately the Visual Studio SDK provides a way at these values. Unfortunately, it's not as straight forward as I would have liked.
Conditionals given an ITextView
Here's a quick extension method I whipped up to pull the "defines" out of the project file given an ITextView/IWpfTextView.
private static IEnumerable<string> Conditionals([NotNull] this ITextView textView)
        {
            if (textView == null) throw new ArgumentNullException(nameof(textView));

            // Get the text document from the text buffer (if it has one)
            ITextDocument textDocument;
            if (textView.TextBuffer.Properties.TryGetProperty(typeof (ITextDocument), out textDocument))
                yield break;

            var componentModel = ServiceProvider.GlobalProvider.GetService(typeof(SComponentModel)) as IComponentModel;

            // Get the VsServiceProvider
            var vsServiceProvider = componentModel?.DefaultExportProvider?.GetExportedValue<SVsServiceProvider>();
            if (vsServiceProvider == null) yield break;

            // Get the DTE ...
            var dte = (DTE) vsServiceProvider.GetService(typeof (DTE));

            ProjectItem projectItem = dte.Solution.FindProjectItem(textDocument.FilePath);
            Configuration activeConfiguration = projectItem?.ContainingProject?.ConfigurationManager?.ActiveConfiguration;

            var defineConstants = activeConfiguration?.Properties?.Item("DefineConstants")?.Value as string;

            if (defineConstants == null)
                yield break;
            
            // DefineConstants entries are listed semicolon and comma delimiated, so we need to split on both.
            string[] constantSplit = defineConstants.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var item in constantSplit)
                yield return item.Trim(); // They can contain whitespace on either end, so we'll strip 'em.
            
        }
Of course, you could get some of those services via an Export and eliminate the GetService / GetExported value calls, but I thought I'd include them since I don't know what you've decided to get from MEF.
Have a lot of fun!

Stay Frosty Visual Studio Extension - Method Block Highlighter, Text Clarity, Background Images and a lot more...

Sunday, August 30, 2015
Updated 9/4/2015 9:00 PM Published to the Extension Gallery (links at the bottom). Thanks for the feedback!
For the most updated information, visit the release page

It's hard to believe but I've been working on this extension for almost a year. That's what happens when you only have a few hours every weekend and the occasional evening to work on a personal project. It started out with a simple desire to add a chiseled effect to the text displayed in Visual Studio. I used to get horrible migraine headaches and that little effect made text visibility at low contrast much better without having to change my syntax highlighting rules. A little later I decided I hated being tied to my multi-monitor setup just to be productive when writing software. So I started working exclusively from my laptop screen, a nice 1920x1080, but still not as nice as having a few portrait 1080P displays and a primary 2K, but with a little bit of a change in how I worked (mostly just getting used to some features I never had needed with unlimited real estate), I was easily as productive on my laptop screen. The advantages of changing scenes means I can work when I feel an inspiration; no more having to tuck myself into a room.
Features
Most of the features of Frosty were designed with two purposes in mind: (1) Make working with code in limited screen real estate easier and (2) Make my environment prettier. Both are quite subjective and I don't expect everyone to agree with my decisions ... in fact, I wrote this for me, so if I'm the only user, I'll still be happy!
Method Blocks
Methods are highlighted with configurable colors, Static, Instance and Constructors. I decided against making those colors configurable in Fonts and Colors because I wanted to be able to control alpha on each, so I've done it via its own Options panel with a color picker. Sure, methods should be small enough to easily visually parse the beginning and end, but we're not always given the privilege of modifying code we've written. By default, constructors are bright, instance methods are dim and static methods are somewhere in between. I'm always looking to get back to a constructor, so I made it stand out a bit. In a God Object or a method that does too much (that, of course, *I* didn't write! :o) ...), finding important bits is easy.
Method Signatures
When the method signature scrolls off the top of the display, it shows up on the left hand side next to the box around the method. Sure, that's available from the drop-down at the top, but my caret isn't always in the method I want to know about. Now it's right in front of me.
Text Rendering
Text rendering in the editor window is also configurable. Much like the great extension, TextSharp, except I only apply the effect to the text editor window (no reason for this other than that I didn't need the rest). You can enable ClearType or kill it, along with other things WPF allows you to tweak that Visual Studio doesn't give you direct control over.
Chiseled Text Effect
It's off by default. This was the original feature that I wanted, but getting it working turned into a several month long adventure with HLSL. Unfortunately, it doesn't render properly in Visual Studio 2015 without Hardware Rendering enabled. The effect is touchy. Colors need to have a bit of grey in them to render and different colors render slightly higher or lower on the baseline. It's a bug I intend to fix, but for now consider it quite "alpha" in nature. That's life!
Configuring
Go to "Stay Frosty" in "Tools|Options". You'll find it *highly* configurable. I like ultimate control over my environment so I tried to leave nothing out as far as customization. Maybe you don't like the features I've implemented? Turn 'em off or change them! Sure, software should be opinionated,... except when its users are developers.
License
I'm not ready to release the source code quite yet, but I will be. The extension is licensed under the Apache 2.0 license. I had to learn quite a bit about Visual Studio Extension development over the last few months and I'm hoping that my experiences with it will help others, so I'm separating out parts into their own projects that can be used by others as utility libraries. Right now, time is keeping me from completing that part, plus I'd like to get a little more feedback from testing in the wild before I throw that out there.
Compatibility
At the moment Frosty supports Visual Studio 2013 and Visual Studio 2015. I'm using the awesome NRefactory library for code parsing in Visual Studio 2013. The 2015 version, of course, uses Roslyn and as a result performs a bit better than the 2013 version. Since I started with 2013, I didn't want to abandon that work and all of the folks who are stuck on the old version.
Caveats - It's Beta
It's beta. If you run into difficulties, please let me know at matthew dot dippel at google's public e-mail service. I'd love to get it right and working. If you want to help out, I'll have the code out on GitHub soon!
There's (at least) one bug. The signatures don't always disappear from the left hand side when the top of the method becomes visible again when scrolling up. And it does use some additional resources when parsing code on Visual Studio 2013 -- it shouldn't get in the way too much on a decent machine (it performs well on my Core i5)
Updates from Initial Feedback
If you use ReSharper (I do!), you can enable their syntax highlighting rules (disabled by default, enable them in options).
You can now enable the Method Signatures to display regardless of whether or not the method signature is scrolled off screen (disabled by default).
Abstract methods are no longer bordered.
Two libraries were removed in favor of the PresentationFramework equivalents.
The error that some were seeing when visiting the options page might be fixed. (I'm not seeing this on my machines)
If ReSharper or the User Classes/Enums/etc Fonts and Colors option is missing, we'll use Identifiers instead of Plain Text.
Fixed an exception that occasionally happened on file load where the width of the adornment would be calculated to a negative number.
Fixed the caching of method signatures so they wouldn't have to be re-created every time they were drawn.

Download the Visual Studio 2015 Edition
Download the Visual Studio 2013 Edition

Quick Fix: Could not load file or assembly when instantiating XAML component (or IoC component) in a Visual Studio Extension Project

Wednesday, July 22, 2015
Symptom
You're writing a Visual Studio extension that involves some XAML or IoC code that references a DLL file. When you attempt to instantiate the control, the debugger pops up with "Could not load file or assembly". You've checked the Fusion log and notice it isn't looking in the folder that contains the extension!
Fix
Add the attribute [ProvideBindingPath] to the class that represents the package (the class that implements the Package base class which is often completely empty).
Why?!
Visual Studio's Extension engine usually figures out where your reference .dll's are and binds them easily, however, when a .dll is referenced in XAML or IoC, it isn't explicit enough for Visual Studio to handle proper binding. The ProvideBindingPath attribute tells the extension engine to look in the extension folder when attempting to resolve dependencies. In my case it was a fancy options page that used XAML for its UI rather than the automatically generated UI.

Nermerle, Nitra, Parsing and Functional Programming

Monday, March 30, 2015
Functional Programming
I started looking into Functional Programming about ten years ago and when F# 1.0 came out, I decided to start paying attention again. I initially explored it as part of a project I had embarked upon to parse a DSL and provide a suitable development environment that a non-developer could use to customize my application. It was a lofty goal and ultimately was scrapped in favor of a much stripped down model that was driven via web forms and a small subset of the features, but the DSL was still available for more complex needs.
Parsing HLSL
Recently that need arose again. I've been messing around with WPF Shader Effects and 2D sprites. No, I'm not developing a game (sorry, no real interest here). The biggest frustration for me has been the lack of debugging information available. My usual process for exploring new languages is a combination of reading/research and poking/reverse engineering. I was the kid that took apart every piece of broken/outdated electronics growing up. After picking up "The Basics", I usually dive right in and write some (terrible) code to see what it does. I'll also read/step through open source code that I think I conceptually understand to validate my understanding.
Hlsl makes my learning process more difficult. I can't step through the code; I can't watch. The way it encodes colors into float4 values is sufficiently different from what you'd expect that predicting what the value would be requires you to know about things like Premultiplied Alpha, mapping textures to float values between 0 and 1. Your college calculus class will come in handy even if you did poorly as most things related to programming/math require you to have a good understanding of how it works even if you don't remember the details. Wolfram|Alpha will will help you if you've forgotten the specifics.
Built-in IDE tools provide barely any information when the HLSL files are rendered by WPF. I'm not sure how valuable they are outside of that, but they're useless here. The larger tools available from NVidia/Intel are overkill and mostly don't cover the areas I was hoping (the NVidia product simply didn't support most of its features on my particular GPU ... Notebooks).
Building a narrow-purpose IDE
I started out exploring WPF ShaderEffects using the wonderful Shazzam. Unfortunately, at the time of this writing, downloading the tool from his site isn't possible but a slightly outdated version (in code only) can be acquired from CodePlex. I tweaked it a bit for my purposes and created a shader effect that I mostly liked. Getting to the fine details, though, was difficult and I knew I'd need more insight into what was going on.
Enter Nemerle, F# and Nitra
The first thing I wanted was better parsing of the code before compile. I went digging around and found a syntax highlighting definition for HLSL. The language has some unique elements, such as Vectors whos parts are accessed via array notation, or .xyzw .agbr notation. It's quite elegant, but my eyes weren't naturally parsing it coming from languages that didn't do that.
The rabbit hole began there. The editor used by Shazzam was a way old version of that used by SharpDevelop. It's since been updated and the core text editor can be grabbed independently from NuGet as AvalonEdit. It works quite differently from the version offered by Shazzam, and syntax highlighting is much more powerful. So I created a Syntax Highlighting Definition for AvalonEdit that would color the .argb items as a variant of gray, red, green and blue and used shades of gray with underlining for the wxyz (I'll get the definition out on GitHub when I have a chance and link to it here).
The Shazzam tool was also missing Intellisense and some of the code signals that Visual Studio provides, so I went looking for a solution there knowing that my old friend F# was probably going to find a way back into my life for this one.
Surprisingly, it was Nemerle and the [Nitra Project from JetBrains]|(http://blog.jetbrains.com/blog/2013/11/12/an-introduction-to-nitra/) that got my attention this time. Tom Jones' Getting Started with JetBrains Nitra specifically covered parsing HLSL! Thanks for that!
It lacked the ability to understand shader2D and had no preprocessor support, but after adding shader2D, I now had a library that easily integrated with AvalonEdit to provide syntax highlighting failures and guidance for repair... All from a concise syntax file.
I wanted something a little more. Inspired a while ago by Bret Victor's Ted Talk, I decided to see if I could create an IDE that would give useful feedback about how the program works while it is being developed. HLSL is a limited purpose language, and WPF ShaderEffects limitations limit it even further. It's the perfect target for an IDE that gives intelligent feedback about the program being written while it is being written. By providing sample inputs and the ability to provide custom inputs for the function, a person can see what the outcome of the code would be in various scenarios,... as close to live as possible.
At this point, I'm building a new HLSL parser specifically targetting the limitations imposed by WPF to ensure that code syntax and rules are followed carefully.
I'm then going to start evaluating ...
Enter the God Awful Visitor Pattern
I'm an OOP guy most of the time. The pattern fits well much of the time and most .Net programmers are comfortable with it. However, The Visitor Pattern hurts my brain.
C# lacks Multiple Dispatch without the DLR. I'm not interested in passing type safety all the way to runtime. The Visitor Pattern is the way around that problem. The pattern is relatively straight forward, but figuring out its intent by looking at the code is painful. F# and Nemerle have pattern matching capabilities and allow multiple dispatch. The resulting code is readable with a small reference to the syntax (Nemerle is easier to read coming from C# than F#, IMHO) and the amount of resulting code is substantially less.
My Plan for Next Time
Unfortunately, this is not my day job. It's Saturday/Sunday Early Morning/Late Evening work. I have no code samples at the moment because I just moved my F# code to Nemerle (and it's so much easier to understand). I hope to spend some time with the parser next weekend when I will have a little more time to poke at it. If I get it to the point I want it, I'll write it up and thow it out on GitHub.
Until then ... Don't panic!
Nemerle documentation can be found here.
Nitra syntax, not terribly well documented, but somewhat easy to follow after going through the Nemerle documentation.

Weekend Adventures in Coding - Visual Studo Customization - Order of Adornment Layers

Saturday, February 14, 2015
When Visual Studio 2010 came out, I started looking into customizing the environment a little beyond what was able to be done with existing extensions. I was looking for the ability to place a background image underneath code and fix some issues with font rendering (particularly around the input font). I had succeeded in getting the background properties set through an extension I wrote (similar to ClaudiaIDE, but with a simple property set instead of adding an adornment layer -- it served my purposes but with some limitations). This morning, I tweaked my extension and brought it up to support 2013 (wow, was that easier than I expected!).

Font rendering was helped by re-running the OSes Clear Type configuration and installing Text Sharp. If this sort of thing is important to you, you also want this free gem: MacType. It causes Windows to render fonts in a way that is more similar to a Mac which I find improves readability substantially. Unfortunately, it doesn't work perfectly everywhere, but some of Visual Studio is affected.

I've decided today to see if I can apply the last bit, a white shadow to text. This is a common effect throughout MacOS/iOS and I find it improves readability (particularly for high-contrast backgrounds).

Here's what I'm looking to apply (apologies for formatting, I'll get the code formatter working again, soon).
item.Effect = new DropShadowEffect
           {
            Opacity = 0.34,
            ShadowDepth = 9,
            Direction = 542,
            BlurRadius = 9,
            Color=Colors.White
           };
Finding an efficient way to do this (preferably without having to hack about with Reflection) has been frustrating, but I've managed to apply all kinds of effects elsewhere while I was attempting to fill in the gaps of the documentation with some reverse engineering.
Default order of Adornment Layers
While poking about, I thought it might be helpful to know the order of the default adornment layers. I just started (re-)evaluating OzCode and it was picked up by the "Exp" (temporary debug instance), so some of these belong to that. I'm also on CU4 so any that aren't documented may belong to that (search PredefinedAdornmentLayers or hit F1 for the documented ones).

CodeBackgroundTextAdornment
vsMergeHighLightSpaceAdornment
Outlining
DiffernceChanges
Difference Space
BraceCompletion
DeltaFullLineAdornment
DeltaNegativeSpaceAdornment
HtmlProvisionalTextHighlight
CurrentLineHighlighter
VsTextMarker
TextMarker
HighlightCommentAdornment
SelectionAndProvisionalHighlight
Inter Line Adornment
Squiggle
LineSeparator
CollaborationMethodEndorsement
ScriptDebuggerSectionDivider
Text
PinnedLayer
vsMergeHighlightSpaceAdornmentAboveText
SmartTag
DragDropAdornmentLayer
Intra Text Adornment
VisibleWhiteSpace
Caret
SimplifyVisualController
PinnableTips
InitialDifferenceWaitingAdornmetLayers
HtmlChrome
I have no idea what I'll be doing with these, but that's the fun of reverse engineering. If you have to do such a task, OzCode is very helpful. It allows searching the contents of objects through several layers and can surface interesting bits to play with. This is, of course, experimental and likely will break between updates, but they've made extending Visual Studio so easy, it's not that bad to tweak between updates/versions. More to come if I figure this out!