Resharper Magic Tricks

Last week, I gave a presentation at the GSP Developers’ Guild’s monthly meeting where I talked about some of the cool (maybe hidden) things that ReSharper can do for you. In this article I’m going to summarize my talk and give links to where you can get the Custom Live Templates, and Extensions. I realize that this post is lessened by not having some of the visuals (no projector, etc).

 

ReSharper Intro

 

ReSharper can do some really cool things. 

 

ReSharper can bulk fix code style issues like variable names conventions.

 

 

 

Code completion is made easier and code simplification is highlighted.

 

It  can also help with if statement nesting or showing you extra code that can be reduced.

 

New to Resharper 9 is finding references on NuGet. I referenced a type from MomentSharp - a DateTime library that I wrote - but I don’t have it referenced in the project. I can use the light blub or Alt + Enter and “Find this type on nuget.org”.

 

Also new to ReSharper 9 is support for C# 6 features like string interpolation.

 

ReSharper can automatically import namespaces.

 

It can apply auto refactoring. I can move a block of code to the CommonStuff class. ReSharper will not only import the namespaces but it will change the references to the function in both classes. But since the code I moved is private, ReSharper tells us that the access will be broken by moving this. No problem; we’ll just Alt + Enter over the now broken code and change the access modifier.

 

Resharper can generate variables or even classes that doesn’t exist based on code.

 

We can add new properties by using prop and pressing tab.

 

I have an undefined type of Album and undefined object _albums. With the Alt + Enter or light bulb shortcuts ReSharper will help us create our model class and our list object.

 

We can easily move string values to a resource file, again with the Ctrl + Shift + R command.

 

ReSharper can be used to quickly create interface members.

 

We can even convert a class into an Interface. Press Ctrl + Shift + R on a class name and select “Refactor this.” From there we can extract class into an interface.

 

ReSharper can refactor method parameters into a class. Place the cursor on method name and use  Refactor This and Extract Class from Parameters.

Custom Live Templates:

I’m all about the shortest path when coding: How can I make the toolset do more for me so I can do more for me?

 

Here’s a couple of examples of live templates I’ve created. You can download these templates from here. To import these settings, save the file, open VS, ReSharper Menu, Manage Options, Import from File. You can also import from the "Raw" Gist.

 

AR - MVC Action Result

dbs - DBSet for CodeFirst Application DB Context e.g. DBSet<Type> Name { get; set; }

jreadys - jQuery Ready with a script tag

jready - must be in a script tag

fa - Font Awesome shortcut

glyphicon - Bootstrap Glyphicon shortcut

collapse - BS Collapse/Accordion

collapsepanel - BS Collapse Panel (meant to go inside above)

row - BS row div

col - BS column, includes col-sm-* and col-md-*

modal - BS modal window

bsip - BS input code block, includes form-group wrapper and an input tag with form-control

id - jquery id wrapper e.g. $("#IDGOESHERE")

 

You can create your own templates from highlighting code. Click the ReSharper Menu -> Tools -> Create Live Template form Selection. You can then setup your own variables as needed. Also take note of the Availability options. You can restrict your templates to be available only under certain conditions. Check out the download link for an examples.

 

Structural Search and Replace

With SSR, ReSharper allows you to find and replace entire blocks of code at a time. For instance, we can search for .Dispose method inside of a finally block instead of using a Using statement. We can highlight this code -> Right Click -> Search Pattern. 

 

You can store often used Patterns to your ReSharper options (ReSharper -> Options -> Code Inspection -> Custom Patterns).

 

You can download my exported SSR templates from this gits (same file as above)

 

Custom Code Inspection

 

You can also use these saved patterns to highlight coding errors based on custom business rules.

For instance, with our Disposable to Using example, we can go to the Code Inspection setting and mark this as a ReSharper hint or error even.

 

On the web side we can mark insecure resource loading as a bad practice. For example, loading Font Awesome over http is fine as long as page or site is loaded that way, but if you were using this in a ecomm solution or a site behind an SSL, this line would throw an error in the browser for mixed content.

 

You can download my exported Code Inspection templates from this gits (same file as above)

 

Value Tracking

 

ReSharper provides inspectors for Value Origin and Value Destination. We can use Ctrl + Shift + Alt + A to bring up “Inspect This”. From this window we can walk through the changes and see where and what happens to our value.

 

Extensions

Who doesn’t love Extensions? If you’re not satisfied with the amount of RAM VS takes up, here’s some can’t-live-without extensions to add to ReSharper (which is an extension).

 

Postfix Templates:

Postfix templates adds a couple of extremely useful templates. We can create a variable in a sort of backwards way.

 

 

We can do a quick foreach on a list.

 

We can wrap a disposable in a using.

 

One of the really cool features is refactoring code to use a variable by copy and paste.

 

ZenSharp

 

 

This extension adds a lot of templates to creating properties, classes and the like.

pps

ppsAge

 

ReSpeller

Handy spell checker for your code and comments.

 

 

Presentation Assistant

While not required for day-in/day-out programming, this plugin will display keyboard commands in a small modal at the bottom of Visual Studio when turned on.

Sweet Shortcuts

Ctrl + T: Navigate to symbol

Ctrl + R, R: Rename all the things

Ctrl + Enter on Class Move To ClassName.cs

Ctrl + Shift + R: Extract To Variable

F12: Navigate to

Shift + F12 Find usage

Ctrl + R, M: Extract Method 

Alt + End: Go to interface implementors

Alt + Home: Go to base class

Alt + Page Up/Page Down go to Next/Previous warning

Ctrl + R, S - Change signature. Add new parameters, create an overload

Ctrl + E, U - Surround with (like try,catch)

Other Cool things

Resharper also provides a Stack Trace Viewer. You can copy a stack trace from Elmah or a YSOD into the stack trace view.

 

What else should be included in this section? You tell me. Leave me a comment below with your favorite ReSharper magic trick. What makes the other programmers envious of your ReSharper know-how?

 

Making Bookmarklets Cool Again

At some point Bookmarklets died and no one played their dirge.

 

If you don’t know what a bookmarklet is, it’s a small piece of javascript code embedded in a bookmark. In some cases, the script injects a javascript file into the the website where the bookmark was clicked. This injection is makes them super useful but is probably also what made them disappear. 

 

XSS (Cross-site scripting) is a topic for another day, but you should beware of it you're not. Go look it up, I’ll wait. No really, this article will still be here when you get back.

 

In the past few weeks, I’ve been creating some interesting bookmarklets to help with my web development. Some of these I’ve found, others I’ve created (mine). To use them, simply drag each headings link to your bookmark bar.

 

Last Modified:

javascript:alert(document.lastModified)

 

 

Want to know the last time an asset was updated? Do note that this bookmarklet only works with static content. It won’t work on server side rendered content like Asp.Net or PHP. If the alert shows you today, right now, it’s most likely dynamically generated.

 

BuiltWith:

javascript:window.location.href='http://builtwith.com/?'+encodeURIComponent(document.location)

 

“BuiltWith is a website profiler, lead generation, competitive analysis and business intelligence tool providing technology adoption, ecommerce data and usage analytics for the internet.”

 

 

BuiltWith shows you what technology a website is built on. Does this site use WordPress? jQuery? Windows Server? Apache?

 

Add jQuery:

javascript:if(typeof jQuery=='undefined') {var s = document.createElement('script');s.type = 'text/javascript';s.src = 'https://code.jquery.com/jquery-2.1.4.min.js';document.getElementsByTagName("head")[0].appendChild(s);}

 

Fiddling with someone else’s website and want to use jQuery in the console? Just use this bookmarklet and poke away.

 

Accessibility:

javascript:(function(){var tota11y=document.createElement('SCRIPT');tota11y.type='text/javascript';tota11y.src='//khan.github.io/tota11y/tota11y/build/tota11y.min.js';document.getElementsByTagName('head')[0].appendChild(tota11y);})();

 

 

This bookmarklet comes courtesy of khanacademy.org. “tota11y helps visualize how your site performs with assistive technologies.”

 

 

Find more at http://khan.github.io/tota11y/

 

WhoIs: (mine)

javascript:window.location.href='https://www.namecheap.com/domains/whois/results.aspx?domain='+encodeURIComponent(window.location.host)

 

Who’s behind that domain name? Get the current domain’s registrar, and register-er, and DNS servers.

 

Note: this could easily be changed from NameCheap to something else, but NameCheap is probably more awesome than your registrar of choice so just leave it.

 

MX Records:(mine)

javascript:window.location.href='https://mxtoolbox.com/SuperToolX.aspx?action=mx%3a'+encodeURIComponent(window.location.host.replace("www.",""))+'&run=toolpage'

MX Toolbox has some seriously cool web tools, including MX Record lookup by domain name. This bookmarklet will take the current domain and pass it on to their SuperTools. You cou easily adapt this to get any of the prefixes that MX Toolbox supports (dns,a,etc) just change action=mx to action=a.

 

 

ASafaWeb: (mine)

javascript:window.location.href='https://asafaweb.com/Scan?Url='+encodeURIComponent(window.location.host)

 

“Welcome to ASafaWeb, the Automated Security Analyser for ASP.NET Websites. The purpose of ASafaWeb is to make scanning for common configuration vulnerabilities in live ASP.NET websites dead easy. To that effect, you don't need anything more than a URL to get started and ASafaWeb will head off and report on anything it can find which is remotely detectable.”

 

While ASafaWeb is directed at .Net sites, there is still some valuable information for you none-.net-ers. Check for custom 404 errors, bad url checking, cookie information and excessive header information.

 

 

+ Pocket:

javascript:(function(){var e=function(t,n,r,i,s){var o=[1095348,2538804,5658233,4265015,2884810,2101921,1898052,5668225,5611958,8200602];var i=i||0,u=0,n=n||[],r=r||0,s=s||0;var a={'a':97,'b':98,'c':99,'d':100,'e':101,'f':102,'g':103,'h':104,'i':105,'j':106,'k':107,'l':108,'m':109,'n':110,'o':111,'p':112,'q':113,'r':114,'s':115,'t':116,'u':117,'v':118,'w':119,'x':120,'y':121,'z':122,'A':65,'B':66,'C':67,'D':68,'E':69,'F':70,'G':71,'H':72,'I':73,'J':74,'K':75,'L':76,'M':77,'N':78,'O':79,'P':80,'Q':81,'R':82,'S':83,'T':84,'U':85,'V':86,'W':87,'X':88,'Y':89,'Z':90,'0':48,'1':49,'2':50,'3':51,'4':52,'5':53,'6':54,'7':55,'8':56,'9':57,'\/':47,':':58,'?':63,'=':61,'-':45,'_':95,'&':38,'

 

“Pocket was founded in 2007 by Nate Weiner to help people save interesting articles, videos and more from the web for later enjoyment. Once saved to Pocket, the list of content is visible on any device — phone, tablet or computer. It can be viewed while waiting in line, on the couch, during commutes or travel — even offline.”

 

Pocket lets you save content to read later. One of the best features about Pocket is that it strips out all the other garbage so you can actually read an article — there’s a novel (pun intended) idea.

 

 

Get Pocket

 

Bootstrap

 

The rest of the bookmarklets are about Bootstrap.

 

 Bootstrap Visibility: (mine)

javascript:$('body').prepend('<span class="visible-lg label label-success">visible-lg</span><span class="visible-md label label-success">visible-md</span><span class="visible-sm label label-success">visible-sm</span><span class="visible-xs label label-success">visible-xs</span>');

 

 

Need to know what Bootstrap thinks the current device size is? Click this bookmark. It will add label to the top of the screen with text like “visible-lg”. 

 

 

Try resizing the browser after adding this. You’ll see it change along with the browser! No guess about which media queries are in use.

 

 

Bootstrap Column Highlighter: (mine)

javascript:$('body').append('<style>*[class^="col-"] { border: 2px solid green; }</style>');$('[class^=col-]').each(function () {    $(this).prepend('<div class="label label-success" style="top: 0; left: 15px;">' + $(this).attr("class") + '</div>');});

 

 

Highlight Bootstrap’s grid system (col-*-*). This bookmarklet will add a border around each element that has a class of col-*-* (col-md-6) and a label displaying what class(es) are applied.

 

This is helpful with the Bootstrap Visibility bookmarklet above so you can tell why an element looks the way it does and what will happen when the viewport is different.

 

 

Bootswatchlet:

javascript:(function(e,a,g,h,f,c,b,d)%7Bif(!(f%3De.jQuery)%7C%7Cg%3Ef.fn.jquery%7C%7Ch(f))%7Bc%3Da.createElement(%22script%22)%3Bc.type%3D%22text/javascript%22%3Bc.src%3D%22//ajax.googleapis.com/ajax/libs/jquery/%22%2Bg%2B%22/jquery.min.js%22%3Bc.onload%3Dc.onreadystatechange%3Dfunction()%7Bif(!b%26%26(!(d%3Dthis.readyState)%7C%7Cd%3D%3D%22loaded%22%7C%7Cd%3D%3D%22complete%22))%7Bh((f%3De.jQuery).noConflict(1),b%3D1)%3Bf(c).remove()%7D%7D%3Ba.documentElement.childNodes%5B0%5D.appendChild(c)%7D%7D)(window,document,%221.3.2%22,function(%24,L)%7Bif(%24(%22.bootswatcher%22)%5B0%5D)%7B%24(%22.bootswatcher%22).remove()%7Delse%7Bvar%20%24e%3D%24(%27%3Cselect%20class%3D%22bootswatcher%22%3E%3Coption%3ECerulean%3C/option%3E%3Coption%3ECosmo%3C/option%3E%3Coption%3ECyborg%3C/option%3E%3Coption%3EDarkly%3C/option%3E%3Coption%3EFlatly%3C/option%3E%3Coption%3EJournal%3C/option%3E%3Coption%3ELumen%3C/option%3E%3Coption%3EPaper%3C/option%3E%3Coption%3EReadable%3C/option%3E%3Coption%3ESandstone%3C/option%3E%3Coption%3ESimplex%3C/option%3E%3Coption%3ESlate%3C/option%3E%3Coption%3ESpacelab%3C/option%3E%3Coption%3ESuperhero%3C/option%3E%3Coption%3EUnited%3C/option%3E%3Coption%3EYeti%3C/option%3E%3C/select%3E%27)%3Bvar%20l%3D1%2BMath.floor(Math.random()*%24e.children().length)%3B%24e.css(%7B%22z-index%22:%2299999%22,position:%22fixed%22,top:%225px%22,right:%225px%22,opacity:%220.5%22,color:%22%23000%22%7D).hover(function()%7B%24(this).css(%22opacity%22,%221%22)%7D,function()%7B%24(this).css(%22opacity%22,%220.5%22)%7D).change(function()%7Bif(!%24(%22link.bootswatcher%22)%5B0%5D)%7B%24(%22head%22).append(%27%3Clink%20rel%3D%22stylesheet%22%20class%3D%22bootswatcher%22%3E%27)%7D%24(%22link.bootswatcher%22).attr(%22href%22,%22//bootswatch.com/%22%2B%24(this).find(%22:selected%22).text().toLowerCase()%2B%22/bootstrap.min.css%22)%7D).find(%22option:nth-child(%22%2Bl%2B%22)%22).attr(%22selected%22,%22selected%22).end().trigger(%22change%22)%3B%24(%22body%22).append(%24e)%7D%3B%7D)%3B

 

 

This bookmarklet will add a small dropdown and allow you to change the site’s theme (sort of). It has Bootswatch’s predefined template selection so you can change the font colors and most of Bootstrap’s default styles.

 

 

 

 

Enjoy and let me know if you have any “must have” bookmarklets. Don’t be ashamed, we’re all in this together. Come on, I know you still use them.

 

Magical one page telerik reporting viewer

In an effort to simplify a project that used Telerik’s Reporting Engine, I wanted to create a single View that listed the available reports and a single View to hold the HTML Report Viewer. In the middle of the project a new requirement was added; you know how that goes. Some reports needed to be able to have querystring parameters come from a related View. This is how I did it. Behold the magic.

 

First I built my View to list the reports. Each report had a link like this:

 

@Html.ActionLink("Click Me", "Report", 
    new { title = "Report Title", path = "Namespace.Path.To.Report" }, 
    new { target = "_blank", @class = "btn btn-primary" })

 

You can get the Namespace path from the code behind file of the report.

 

Set up an ActionResult like this:

 

public ActionResult Report(string path, string title)

{

    ViewBag.ReportPath = path + ", ProjectNS";

    ViewBag.Title = title;

    return View();

}

 

ProjectNS should be your root Namespace. 

 

And the matching View:

 

@using Telerik.Reporting

@using Telerik.ReportViewer.Mvc

 

@{

    Layout = "~/Views/Shared/_ReportsLayout.cshtml";

}

 

@functions {

    private ReportSource GenSource()

    {

        var typeReportSource = new TypeReportSource {TypeName = ViewBag.ReportPath};

 

        if (Request["path"] == "Namespace.Path.To.Report" && !string.IsNullOrEmpty(Request["id"]))

        {

            typeReportSource.Parameters.Add(new Parameter("Id", Request["id"]));

        }

        

        return typeReportSource;

    }

 

}

 

@(Html.TelerikReporting().ReportViewer()

        .Id("reportViewer1")

        .ServiceUrl("/api/reports/")

        .TemplateUrl("/ReportViewer/templates/telerikReportViewerTemplate.html")

                    .ReportSource(GenSource())

        .ViewMode(ViewModes.INTERACTIVE)

        .ScaleMode(ScaleModes.SPECIFIC)

        .Scale(1.0)

        .PersistSession(false)

)

 

What’s cool about this code block is that you can craft Querystring parameters to pass in values to the report from another page. Like so:

 

/Report?title=Title&path=Namespace.Path.To.Report&id=42&active=True

 

Not only will the Report view load the correct report, it will also load in these default values:

 

 

 

Using Grunt to JSHint and JSCS your JavaScript code.

This is part 2 to my last post, which you’ll want to read first since I’m going to assume some of your gruntfile.js has some necessary settings.

 

Using Grunt to JSHint (Code Quality) and jscs (Code Style checker) your JavaScript code.

 

In this post, I'm going to show you how to get Gruntjs to check your JavaScript Code for quality in Visual Studio 2015.

 

Add this to your package.json file.

 

"grunt-jscs": "latest",
"grunt-contrib-jshint": "latest"

 

This will add JSCS and JSHint to your node_modules folder and let us run our tasks.

 

Add

 

grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-jscs');

 

to gruntfile.js at the bottom with the rest of your loadNpmTasks

 

Read More

How to get Grunt to compile your LESS files on save, and at build, in VS 2015.

I’m trying out Visual Studio (VS) 2015, which at the time of this writing, is in RC. Like most developers, the first thing I do with a shiny new VS is to install my tools and plugins. Of course I got Resharper (R#) installed and the PostFix Templates extension for R# installed.

 

Lately, I’ve been playing around with Win 8/10 JS apps that I’ve started in VS 2015, but I hadn’t opened any existing applications in VS 2015 since I work on some team projects. VS 2013 had one-way project upgrading and I had some issues with a previous team where not everyone was on the same version of VS.

 

Today, I had both VS 2013 and 2015 opened at the same time. This caused some issues with R#’s licensing platform so I made the leap and opened one of my web projects in VS 2015.

 

Let me back up a little: since I mostly do web development, I work with LESS quite a bit. Once upon a time I used a Post Build event to execute an npm command to compile my LESS files. As most web developers do, I have Web Essentials (WE) installed and at some point it finally stopped giving me issues with Bootstrap’s LESS files.

 

Moving forward: I had opened a web application in VS 15 and tried to save a LESS file. I noticed that it didn’t recompile the LESS file to CSS. That’s when I noticed that I had forgotten to install WE! Off to the VS Extension Manager! What’s this? WE installed and in this version, they’ve stripped the compilers out.

 

Which brings me to writing this post:

 

How to get Grunt to compile your LESS files on save, and at build, in VS 2015.

 

Read More


About Me

Hello, I’m Jonathan Peterson (aka Eonasdan)! I’m a web developer and CEO of Paladin Cloudware.

I have over 8 years of experience developing a wide array of web applications and websites. In my free time, I contribute to several open source projects.

As a die-hard developer, you’ll find me programming in my head on the rare occasions when I'm without an Internet connection.

Find me on:

Tags

telerik, ReSharper, Tips And Tricks, less, grunt, c#, visual studio, code quality, visual studio 2015