Minifying and publishing CSS and JavaScript using Visual Studio 2013 and LESS - visual-studio-2013

When I publish my MVC web app I can see that the published location gets the original js and css files, it does get minified when I run it (I can see it in view source)
This is what I'm doing:
BundleTable.EnableOptimizations = true;
bundles.UseCdn = false;
var cssTransformer = new StyleTransformer();
var jsTransformer = new ScriptTransformer();
var nullOrderer = new NullOrderer();
var cssBundle = new StyleBundle("~/bundles/css");
cssBundle.Include("~/Content/Site.less", "~/Content/bootstrap/bootstrap.less");
cssBundle.Transforms.Add(cssTransformer);
cssBundle.Transforms.Add(new CssMinify());
cssBundle.Orderer = nullOrderer;
bundles.Add(cssBundle);
var sampleCssBundle = new StyleBundle("~/bundles/sampleCss");
sampleCssBundle.Include("~/Content/sample.css");
sampleCssBundle.Transforms.Add(cssTransformer);
sampleCssBundle.Transforms.Add(new CssMinify());
sampleCssBundle.Orderer = nullOrderer;
bundles.Add(sampleCssBundle);
var sampleJsBundle = new ScriptBundle("~/bundles/sampleJs");
sampleJsBundle.Include("~/Scripts/sample.js");
sampleJsBundle.Transforms.Add(jsTransformer);
sampleJsBundle.Transforms.Add(new JsMinify());
sampleJsBundle.Orderer = nullOrderer;
bundles.Add(sampleJsBundle);
will I get a better performance if I deploy a minified version of the files to the published location?
(for example: myFile.min.js and myFile.min.css)
is there a native way to generate the files in Visual Studio so I can publish it minified?
(I could view each minified file and save it as myFile.min but I like to have an automated way to do it)
Thanks in advance.

I'm always excited to see someone tuning their website performance!
1) As long as you are referencing the bundles (and not the published files), publishing minified files will have negligible impact. The bundling system reads the files only once and caches a minified and bundled version in memory. The resulting bundle is identified with a hash that is included in the page and allows browser and proxy caching of the bundle. When your published files change, the bundle will be updated and the page will use the new bundle hash.
This answer has additional information on caching.
If you are interested in automating the "first request" explore Application Initialization
2) The Web Essentials extension by Mads Kristensen has minification support for CSS and JavaScript. As of Visual Studio 2013 Update 4 there is no built-in tooling that would create minified files.

Related

How to programatically add an existing project to a solution folder in Visual Studio

I have a solution that I want to programatically add an existing project to.
Opening the solution using envdte automation is relatively easy
var envDteType = Type.GetTypeFromProgID("VisualStudio.DTE.15.0");
var envDte = Activator.CreateInstance(envDteType, true);
var dte2 = (DTE2)envDte;
var solution = (Solution4)dte2.Solution;
solution.Open(filename);
But adding an existing project to a solution folder is not.
Note this isn't using a template which is what most google results give
Using
var referencesFolder = solution.AddSolutionFolder("References");
referencesFolder.ProjectItems.AddFromFile(fullPathToCsProj);
Adds the project file as a plain old file, not a CSharp project.
The use case is we are in nuget update hell with our library management and will dereference nuget and add a direct project reference instead. There are around 55 projects that require hundreds of dereferences hence the automation.
The trick is to add cast the returned project to a SolutionFolder (note the .Object)
var referencesFolder = (SolutionFolder) solution
.AddSolutionFolder("References")
.Object;
referencesFolder.AddFromFile(fullPathToCsProj);
This gives access to AddFromFile on the root entity which adds the project properly

How to combine TypeScript output into multiple files in VisualStudio

I'm working on a web application which contains multiple SPA (AngularJS) applications, the front end code is TypeScript. I like the VisualStudio feature which combines JavaScript output into one file as I don't want too many JavaScript files. Is there a way to configure it so it still combines the files, but creates a few of them, one per SPA, let's say on folder basis?
I'd preferably like it done by VS, without any external tools.
Thanks
You can for sure. Currently, there are two options which are widely accepted (sorry for lay-out, markup does not seem to love me):
ASP.NET Bundles (in Visual Studio by default, .\App_Start\BundleConfig.cs - for more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862):
bundles.Add(new ScriptBundle("~/bundles/modernizr")
.Include("~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap")
.Include("~/Scripts/bootstrap/3.0.0/bootstrap.js",
"~/Scripts/respond.js"));
gulp-concat (external, but quite easy to implement):
/** bundle and uglify app JS output files. */
gulp.task('bundle-app-uglify', ['compile-app'], function () {
// concat and uglify source scripts
gulp.src(config.allAppJsFiles)
.pipe(uglify())
.pipe(concat(config.appBundleNameMinified))
.pipe(header(config.libraryHeaderTemplate, {
organization : config.libraryOrganization,
url: config.libraryUrl,
license: config.libraryLicense,
version: config.libraryVersion,
currentDate: new Date().toISOString()
}))
.pipe(gulp.dest(config.bundleFolder));
});

Visual Studio web deploy - simple way to include build info?

I have an ASP.NET site that I am deploying to Azure Websites. I have a production and staging environment there and it is easy to get lost which is which. During the web deploy ("Publish") from Visual Studio, is there some simple way to deploy some kind of build info that I could display either via the site itself or through the Azure Portal?
You can add a version number to your assembly by adding this line to AssemblyInfo.cs file
[assembly: AssemblyVersion("1.0.*")]
more details here and here
you can then expose it in your site however you want, maybe a hidden tag, some sort of debug info page, or write it to a file on Application_Start that you can look at later
for example in global.asax you can have
protected void Application_Start()
{
using (var writer = new StreamWriter("version.txt")
{
var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
writer.WriteLine(version);
}
}
Generating a text file with current date as a post-build step was the easiest solution I found.

How can I create a new Windows Phone 7 assembly from scratch using CCI or Mono.Cecil

I am working on a tool to generate assemblies for WP7. I am doing this from the full framework. Since Reflection.Emit doesn't work with WP7 but either CCI or Mono.Cecil do I am wondering if there is a way to create new assemblies from scratch. I already know that I can modify existing assemblies, but being able to create one would be pretty useful.
I guess a workaround would be to generate an empty assembly in visual studio and keep it as a template, but I think that there should be a better way.
It's pretty easy to do with Mono.Cecil:
using Mono.Cecil;
using Mono.Cecil.Cil;
class Demo
{
static void Main()
{
var winphoneAssemblies = #"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0\Profile\WindowsPhone";
var assemblyResolver = new DefaultAssemblyResolver();
assemblyResolver.AddSearchDirectory(winphoneAssemblies);
var winphoneCorlib = assemblyResolver.Resolve("mscorlib");
var module = ModuleDefinition.CreateModule("Test", new ModuleParameters
{
AssemblyResolver = assemblyResolver,
Runtime = TargetRuntime.Net_2_0,
Kind = ModuleKind.Dll,
});
// trick to force the module to pick the winphone corlib
module.Import(winphoneCorlib.MainModule.GetType("System.Object"));
var type = new TypeDefinition("Test", "Type", TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Abstract, module.TypeSystem.Object);
module.Types.Add(type);
var method = new MethodDefinition("Identity", MethodAttributes.Public | MethodAttributes.Static, module.TypeSystem.Int32);
method.Parameters.Add(new ParameterDefinition("i", ParameterAttributes.None, module.TypeSystem.Int32));
type.Methods.Add(method);
var il = method.Body.GetILProcessor();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ret);
module.Write("Test.dll");
}
}
A few things to note:
The need to create the module with an assembly resolver targeting the winphone assemblies.
A little trick to make sure the module picks up the proper winphone mscorlib (will be fixed in the next version of Cecil).
Silverlight assemblies have the metadata version of the .net 2.0 framework.
It's worth pointing out that while you may be able to generate dynamic assemblies from within the phone's runtime using alternate framework's, you're not goint to be able to load / execute them. Those APIs will throw an exception if executed by application code.

what is the correct build action for windows phone 7 image files?

I've been working on a Windows Phone 7 app, and after a bit of Googling it seems that for images that I have added to the Visual Studio project, I need to set the build action to "Content" in order to be able to reference the images in my app.
However, the Windows Phone List Application project template includes an image (ArrowImg.png) that has its Build Action set to "Resource", and is still available to be referenced from the application.
I was wondering if anyone could confirm that we should definitely be using the Content build action, or whether there is some way to access images added to a project with the Resource Build Action as shown in the project sample, which we should be using instead?
If you set the action to "Content" the image is included "as-is" in the XAP.
If you set the action to "Resource" the image is embedded into a shared DLL.
In a lot of situations you can use either. There may be a performance, or other, issue with using one rather than another but I'm not aware of and have never noticed any.
For what it's worth, unless I need to specifically make it a resource, I use content.
With the current (Beta) tools, I have seen VS complain that images directly referenced in XAML should be set to "Resource" (if set to "Content") but the app works fine with either. Hopefully this is an issue which will be addressed in the RTM tools.
For more information see the discussion in What are the various "Build action" settings in Visual Studio project properties and what do they do?
Either build action is correct.
Also worth looking at when resolving issues relating to build action is the pathing you use.
I've seen a fair few people running into trouble with this because they assume they've set their build action inappropriately.
You can set the build action either way to suit your requirements of when to incur the load time cost, you just need to adjust the pathing to suit.
Some more info on the topic from this post.
Set source to image in C#
You can liken content to the lazy
loading version of resources.
The difference is you will incur the
performance hit of all resources when
the assemblies are loaded to start
your app.
Content, on the other hand, the
performance hit is deferred to when
you use it.
Which is more suitable will vary on a
case by case basis.
Note also that the pathing to
reference resources and content is
different as can see here.
//Uri uri = new Uri("/Resources/Images/MyImage.jpg", UriKind.Relative); // Content
Uri uri = new Uri("/PhoneApp;component/Resources/Images/MyImage.jpg", UriKind.Relative); // Resource
BitmapImage imgSource = new BitmapImage(uri);
image1.Source = imgSource;

Resources