Using Static Methods from the .NET Framework in MSBuild – a List of All Property Functions

by Oliver 9. June 2016 20:20

In the MSBuild deployment script for our discoverize portals we use a number of useful functions from the .NET framework, e.g.: $([System.IO.File]::Exists($file)) $([System.IO.Path]::GetFileName($(Destination))) $([System.IO.Directory]::GetDirectories("$(Folder)")) $([System.DateTime]::Now.ToString($(TimestampFormat))) These methods are called Property Functions and have been made available for use in MSBuild scripts since version 4. Here's the full list of .NET framework types whose static methods or properties you can use almost anywhere in you MSBuild scripts: System.Byte System.Char System.Convert System.DateTime System.Decimal System.Double System.Enum System.Guid System.Int16 System.Int32 System.Int64 System.IO.Path System.Math System.UInt16 System.UInt32 System.UInt64 System.SByte System.Single System.String System.StringComparer System.TimeSpan System.Text.RegularExpressions.Regex Microsoft.Build.Utilities.ToolLocationHelper There are a few rather useful methods from some more types that you can also use: System.Environment::CommandLine System.Environment::ExpandEnvironmentVariables System.Environment::GetEnvironmentVariable System.Environment::GetEnvironmentVariables System.Environment::GetFolderPath System.Environment::GetLogicalDrives System.IO.Directory::GetDirectories System.IO.Directory::GetFiles System.IO.Directory::GetLastAccessTime System.IO.Directory::GetLastWriteTime System.IO.Directory::GetParent System.IO.File::Exists System.IO.File::GetCreationTime System.IO.File::GetAttributes System.IO.File::GetLastAccessTime System.IO.File::GetLastWriteTime System.IO.File::ReadAllText The general pattern to call a property method is: $([Class]::Method(Parameters)). Beyond the above mentioned methods, MSBuild offers some more helpful ones that are invoked on the MSBuild pseudo class: [MSBuild]::DoesTaskHostExist(string runtime, string arch) [MSBuild]::GetDirectoryNameOfFileAbove(string p, string f) [MSBuild]::GetRegistryValue(...) [MSBuild]::GetRegistryValueFromView(...) [MSBuild]::MakeRelative(string path1, string path2) [MSBuild]::ValueOrDefault(string value, string default) [MSBuild]::Escape(string unescaped) [MSBuild]::Unescape(string escaped) [MSBuild]::Add(double a, double b) [MSBuild]::Add(long a, long b) [MSBuild]::Subtract(double a, double b) [MSBuild]::Subtract(long a, long b) [MSBuild]::Multiply(double a, double b) [MSBuild]::Multiply(long a, long b) [MSBuild]::Divide(double a, double b) [MSBuild]::Divide(long a, long b) [MSBuild]::Modulo(double a, double b) [MSBuild]::Modulo(long a, long b) [MSBuild]::BitwiseOr(int first, int second) [MSBuild]::BitwiseAnd(int first, int second) [MSBuild]::BitwiseXor(int first, int second) [MSBuild]::BitwiseNot(int first) The smart thing about those arithmetic methods is that MSBuild converts string values to a matching number type on the fly, so there's no need for any explicit type conversion. And that would be the whole spectrum of property functions in MSBuild. For further reading, please turn to the official documentation on the MSDN. Happy coding! photo credit: Paddington Reservior Gardens Roof via photopin (license)

Anatomy Of a URI

by Oliver 18. December 2015 13:40

I keep wondering what's behind the properties of the .NET URI class. So here, once and for all, by courtesy of LINQPad4, a breakdown of the different properties and values of a URI: Happy coding!

enjoyed the post?

Tags:

.NET

ASP.NET, OWIN and Katana

by Oliver 12. November 2014 13:42

This is a short overview post on OWIN, which (I quote from its homepage) […] defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools. In other words, the OWIN specification aims to put an end to monolithic solutions like ASP.NET WebForms or even ASP.NET MVC in favor of creating smaller, more lightweight application components that can be chained together to configure an application that does exactly what the author intends it to do – and nothing more. In addition, OWIN simplifies development of alternative web servers that can substitute IIS, e.g. Nowin, or Helios, a promising .NET server alternative on top of IIS but without the heavy, 15-year old System.Web monolith (here's a good review of Helios by Rick Strahl). Katana is a Microsoft project that contains OWIN-compatible components… […] for building and hosting OWIN-based web applications. For an overview of Katana look here. The Katana architecture can be found on the right and promotes exchangeability of components on each layer. It turns out that ASP.NET vNEXT (github repo here) continues the work that has been done by Microsoft in that direction. Here's an enlightening quote by David Fowler, development lead on the ASP.NET team: vNext is the successor to Katana (which is why they look so similar). Katana was the beginning of the break away from System.Web and to more modular components for the web stack. You can see vNext as a continuation of that work but going much further (new CLR, new Project System, new http abstractions). The future of ASP.NET looks bright – especially for developers! Check out my last post on ASP.NET vNEXT and Docker, too.

Creating PDFs of HTML

by Anton 7. November 2014 15:47

For our new time tracking web application (which not yet live) we need the functionality to create a PDF report. Since we use AngularJS to generate the HTML for the reports, I thought it would be nice to just convert that HTML via JavaScript into a PDF. The search for a solution pointed me to jsPDF – a pretty good tool for creating PDF via JavaScript. But its capabilites to convert HTML into PDF are limited (as of late 2014). We needed to convert a HTML table with all its styles into a PDF. I added jsPdfTablePlugin into the mix, but it still did not look good. So we abandonded the JavaScript way, and let the backend generate the PDF. I added an MVC view that displays the report, which is then captured via wkhtmltopdf. We already knew this process since we use it in our platform tool discoverize generating invoices. It works smoothly.

enjoyed the post?

Tags:

JavaScript | .NET | C# | PDF

Visual Studio 2013 Hidden Gems

by Oliver 17. October 2014 23:13

This post is one of several summarizing some of the sessions I attended during the .NET Developer Days conference in October 2014. Check out the rest of them. Here are my notes from a whole day of sessions diving deep into Visual Studio and its possibilities, lead by Kate Gregory: Window positioning When drag'n'dropping windows you can drop them in any place you like, even in a place where VS suggests to dock it to another window group, by holding down the CTRL key and then releasing the mouse button. Using the Start Page Probably 3% of all developers use it but it's gotten better over the years. You can now pin projects to it so they won't fall of the most recently used list, you can remove unneeded projects by right clicking or open its folder if you forgot where you keep it. Also, the start age hides itself once you open a project or a file so you don't have to close it by hand anymore. Navigating Code If you want to go to the definition of a symbol just get your cursor on it and press F12 which is the shortcut for Go To Definition. That will open the file that contains the definition of given symbol. Now, if you want to drill down into a deeper hierarchy and don't care for the intermediate definitions, give Alt+F12 a try – it's the shortcut for Peek Definition and it will open the definition of the given symbol in an iframe type of window right inside the code you're looking at. You can then use that window to follow further definitions without leaving the current point of interest. [Can't find that menu item in the Express edition, though.] Also, give bookmarks a try! There's a bookmark manager where you can give your bookmarks a name, group them into folders and the like. Quite helpful to quickly find your way around a large codebase or for presentations. Finding things There's great inline find window by now in VS that you can control from your keyboard in no time. Use Ctrl+F to open it with the word prefilled that your cursor is currently on or use Ctrl+F3 to search for the next occurrence of the word your cursor is on. This little tool is really worth getting to know well because it can save you a lot of time when looking for stuff or replacing it. Have you noticed the search text box at the top of the Solution Explorer? There's even a shortcut to get there so you don't have to take your hand off the keyboard. Be prepared to find even more search boxes here and there, e.g. the Error List has one, too! Application Lifecycle Management (ALM) Visual Studio Online is a new one-stop solution for hosting projects and collaborating on them in the cloud. It basically offers cloud-based TFS instances. The basic plan is free for up to 5 users in a project with an unlimited number of stakeholders, who are allowed view burndown charts, backlogs, Kanban, and task boards, and may even create new Work Items. It supports, of course, TFVC but also Git for source control. In Visual Studio, use the Team Explorer window to work with your remote TFS, e.g. your Visual Studio Online account, but you can choose to manage your project through a web browser just as well. There's powerful work item editor available online, have a look and take a minute to grasp what all it offers: I'd call it impressive. There's really a ton of features here, and no doubt there are other tools out there to do the same thing. What really cuts it for me: Visual Studio Online is free for up to 5 users and an unlimited number of stakeholders. The integration with Visual Studio is seamless. [You can do pretty much all of the management work either in VS or online.] Sign out of VisualStudio.com If you're logged into VisualStudio.com you can log out by opening the drop-down menu next to your login name, choosing "Account settings…" and there clicking "Sign out". Beware that you have to be logged in with a Microsoft account if you want to use the Express version for longer than 30 days. Debugging I'll just put stuff into a list here for better readability: Have you  met the Autos window? Seems not to be included in the Express version but when hitting a breakpoint it offers insight into all variables used on the current line, the previous line and after exiting a function, shows its return value even if you didn't assign to any variable! The Locals window captures the values of all variables defined in the current scope without the need to add them to the Watch window. Press the CTRL key to temporarily hide the variable inspector popup window: -> Pin values from the above window so you'll keep their values in view – even during the next debugging session! Set your cursor on a line of code and choose Run To Cursor from the context menu to continue running your code up until the line with the cursor. Wow! Or choose Set Next Statement to skip all code from the current breakpoint onwards and jump to the selected line. Wow²! Edit + Continue is also great but works only in 32-bit mode :-| IntelliTrace (in the Ultimate edition) allows you to capture execution traces of your software on a client machine and debug (through replaying) the same set of instructions inside your local VS – Kate Gregory called it Time Travel Debugging ;-) That's it from the first day. Happy developing!

.NET Developer Days in Wroclaw

by Oliver 15. October 2014 19:39

I'm currently attending the first .NET Developer Days conference in Wrocław, Poland, and will put up a few posts with my notes from some of the sessions I was able to attend. The conference took place from 14.10. to 16.10.2014 in the Wrocław Stadium. Here's a list of all posts (I'll update the links as soon as I finish a given post): Visual Studio 2013 Hidden Gems ASP.NET vNEXT SQL Server Data Tools: An Intro Continuous Deployment WebAPI, OData There's already been a lot of input and the third day is still ahead of me! I hope I'll be able to update the above list soon. Happy Coding!

Sending DateTime Instances From a .NET Server to a JavaScript Client and vice-versa

by Oliver 20. September 2014 21:47

At teamaton we're currently developing our own Time Tracking tool that we'll be using instead of KeepTempo as soon as it's good enough. We even plan on making it accessible to the public later but that's a different story. We chose Angular.js to develop the frontend and now want to synchronize our time tracking records with our ASP.NET WebAPI backend. One property of such a record is the date and time it was created at, createdUtc. Let's look at how we can send those date-time values to the server and back again. Some Background on Date and DateTime JavaScript Date instances are seeded at 01/01/1970 00:00:00 and can be instantiated by passing to the Date() constructor the number of milliseconds that have passed since that moment in time. Date.now() will directly output this number, at the moment of writing these words it returned the value 1 411 240 284 042. This value is what all other representations of a given Date instance will be based on. In .NET we have the DateTime type and its seed value is 01/01/0001 00:00:00. Internally, DateTime instances count time in Ticks, where one tick equals 100 nanoseconds, i.e. 0.000 000 1 seconds, thus delivering a theoretical precision of 10000 times that of the JavaScript equivalent. When writing these words, the current number of Ticks of DateTime.Now was 635 468 449 058 588 764 (I use LINQPad to execute C# code snippets). How to Convert JavaScript Date to .NET DateTime So how do we convert those values into each other? If we decide to send the number of milliseconds in a given JavaScript Date instance to our .NET server we can reconstruct an equivalent DateTime instance by seeding it with 01/01/1970 and just adding the milliseconds we got from the client to it: Record.CreatedUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds); Going the other way, we actually need to get hold of a TimeSpan instance which has the property TotalMilliseconds that gives us what we want. We'll do that by substracting a DateTime instance representing the 01/01/1970 from the DateTime instance we want to send to the client: (Record.CreatedUtc - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds The code looks a bit ugly because we take care to work with UTC dates so that our code will run the same for clients and servers around the world. It's a very good idea to work with UTC dates internally and only convert them to local dates when you want to display them somewhere. … or Just Use Date Strings There's another way to transfer date objects between JavaScript and your server: using a standardized string representation that both sides will be able to generate and parse. In JavaScript you would use Date.toISOString() and in .NET DateTime.ToString("O") (see the MSDN for the O format string). Happy coding!

Learning Powershell

by Oliver 30. May 2014 21:34

Today, I finally decided that I want to get to grips with PowerShell and have it available in my toolbox for those everyday developer tasks. For a fresh start, I wanted to make sure I'm running the latest and greatest of PowerShell, but how do I find out which version I have installed? What version am I running? Just fire up a PowerShell instance and type $psversiontable or $host.version: PS C:\Windows\system32> $psversiontable Name                           Value ----                           ----- PSVersion                      4.0 WSManStackVersion              3.0 SerializationVersion           1.1.0.1 CLRVersion                     4.0.30319.18444 BuildVersion                   6.3.9600.16406 PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0} PSRemotingProtocolVersion      2.2 PS C:\Windows\system32> $host.version Major  Minor  Build  Revision -----  -----  -----  -------- 4      0      -1     -1 Actually, when I ran this I didn't have the 4.0 version installed yet. So where did I get it? How to install Powershell 4.0 (the newest version as of mid 2014)? Go here and choose the right link for you: How to Install Windows PowerShell 4.0. That's it. Make use of great tooling: use the ISE Last but not least, especially for those of you who like me are just getting started, make sure you're using the great Integrated Scripting Environment (ISE) that comes bundled with PowerShell: Now, get scripting!

Using Unit Tests to Satisfy SpecFlow Scenarios

by Anton 2. October 2013 15:16

Ususally we spec out features using SpecFlow. Then we write out the step definitions and code the feature (or vice versa). When we programmed the “export entries” feature for the portal management area of discoverize, we did so using TDD (test driven development) with unit tests. Since it is an MVC project, we could mock the controller (and the services needed). It all went well, and in the end the feature was coded. Yet, the SpecFlow scenario had no step definitions to fulfill it. @unittestScenario: Export every property from every entry Given I have 2 entries When I export all properties Then I get a file with 3 lines And the first line are the column names, that is the property names And each other line represents the data of one entry Usually we write steps that follow links and push buttons in the web interface – as the user would do. This time – since we already had good coverage of the controller action – we decided to hook up the unit tests as the step definitions. This is quite easy if you know how. We used the @unittest tag to suppress starting the IIS Express and browser for this scenario. Since our unit tests are in a different project than the SpecFlow tests we did everything according to this documentation. After a little refactoring in the unit tests to extract appropriate methods for the steps and adding the step attributes the SpecFlow scenario went green. [Then(@"I get a file with (\d+) lines"), Scope(Tag = "unittest")]public void FileHasLines(int numberOfLines) { var lines = _exportText.Split('\n'); Assert.AreEqual(numberOfLines, lines.Count());}

Optimize Images for Your Website

by Oliver 17. June 2013 13:59

This is just a short post to draw your attention to a sweet tool I've just discovered: PNGGauntlet. It runs on Windows using the .NET 4 framework and is as easy to use as you could possibly wish. Also: it's completely free to use. Convert Your Existing PNGs For starters, we'll just convert some existing PNGs – can't really do any harm with that. In the Open File dialog, there's an option to filter for only .png files. You can choose many of them at once: If you provide an Output directory, the optimized files will be written to that destination. But: the tool also has the option to overwrite the original files, which is awesome if you use some kind of source control (and thus have a backup) and just want to get the job done. During my first run, using the 8 processing threads my CPU has to offer, … … I got savings from 3% to 27%: PNGGauntlet also tells me, that in total I saved 4,52 KB. If those were all images on your web site, that would be a not so bad improvement, especially when you get it investing about 2 min of your time and no extra expenses! Real Savings Running PNGGauntlet on the sprites that we use for Camping.Info, we were really surprised: out of 172 KB it saved us over 31%, a whole 54 KB! Now that's an improvement that on a slightly slower connection will already be noticeable. We'll definitely check the rest of our images for more savings. Convert Other Image Formats You can also choose to change your images format to PNG if you're in the mood. I tried converting all GIFs in the Orchard CMS Admin theme to PNGs and went from a total of 24 KB for 20 files to less than 17 KB with no loss of quality – an over 30% saving! Just beware that you'll need to change the file references in your project to pick up the new PNGs. Roundup Easy, fast and cheap (as in free) image optimization doesn't have to be magic anymore – today anyone can do it. Check out PNGGauntlet to try for yourself. There's really no excuse not to!

About Oliver

shades-of-orange.com code blog logo I build web applications using ASP.NET and have a passion for jQuery. Enjoy MVC 4 and Orchard CMS, and I do TDD whenever I can. I like clean code. Love to spend time with my wife and our daughter. My profile on Stack Exchange, a network of free, community-driven Q&A sites

About Anton

shades-of-orange.com code blog logo I'm a software developer at teamaton. I code in C# and work with MVC, Orchard, SpecFlow, Coypu and NHibernate. I enjoy beach volleyball, board games and Coke.