How to use SASS in Dart editor - sass

Anyone have a canned solution for integrating SASS or another CSS preprocessor into the Dart editor? Seems to require a custom build.dart, which I would rather copy than code. Thanks.

I stumbled upon this a few days ago
Sass integration for pub

Here is a build.dart file with basic support for SASS:
import 'dart:io';
void main(List<String> args) {
for (String arg in args) {
if (arg.startsWith('--changed=')) {
String file = arg.substring('--changed='.length);
if (file.endsWith('.scss')) {
var result = Process.runSync('sass',
[ '--line-numbers', file,
file.substring(0, file.length - '.scss'.length) + '.css']);
if (result.exitCode != 0) {
// report error (SASS seems to only report first error)
// split error lines
var lines = result.stderr.split('\n');
// escape quotes in error message on first line
var error = lines[0].replaceAll('"', r'\"');
// extract line number from second line
var numMatch = new RegExp(r'\d+').firstMatch(lines[1]);
var lineNum = numMatch == null ? 1 : num.parse(numMatch.group(0));
// Report error via JSON
print('[{"method":"error","params":{"file":"$file","line":$lineNum,"message":"$error"}}]');
}
}
}
}
}

During development (with Dart Editor or another editor...), just use sass the way it's meant to be used, in your directory project :
sass -w .
Put the CSS generated files in the ignore list of your source code management system (aka .gitignore for git).
And for dart2js compilation, use the sass pub package : http://pub.dartlang.org/packages/sass

Related

How to show Analyzer errors/warnings during msbuild in VS Dev Cmd & using MSBuildWorkspace

I'll explain the situation with an example.
Suppose I have created a Roslyn Analyzer which throws Error when Class name is TestClass. Analyzer code is as below:
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(Method, SyntaxKind.ClassDeclaration);
}
private static void Method(SyntaxNodeAnalysisContext context)
{
var node = (ClassDeclarationSyntax)context.Node;
var name = node.TryGetInferredMemberName();
if(name == "TestClass")
{
context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation()));
}
}
So i install the Analyzer nupkg in some ConsoleApp project. Console project has following code in Program.cs file
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
class TestClass
{
static void test()
{
Console.WriteLine("TestClass");
}
}
}
Now if i build the ConsoleApp project in Visual Studio then i get Error as "TestClass name not to be used" which is fine.
But when i try to build the same project using msbuild command in Developer Command Prompt for VS 2017 i don't see any error from Analyzer. I want that all the errors shown in Error list in VS should be shown in Dev Cmd.
My end goal is to create a stand-alone code analysis tool project and then use MSBuildWorkspace to compile ConsoleApp project and get the analyzer errors/warnings. Part of code is as below:
var filePath = #"C:\Users\user\repos\ConsoleApp\ConsoleApp.sln";
var msbws = MSBuildWorkspace.Create();
var soln = await msbws.OpenSolutionAsync(filePath);
var errors = new List<Diagnostic>();
foreach (var proj in soln.Projects)
{
var name = proj.Name;
var compilation = await proj.GetCompilationAsync();
errors.AddRange(compilation.GetDiagnostics().Where(n => n.Severity == DiagnosticSeverity.Error).ToList());
}
var count = errors.Count();
Above code does not show errors/warnings from analyzer.
How can i achieve this?
Thanks in Advance.
To show analyzer errors/warnings during msbuild in VS Dev Cmd, you just have to pass rebuild switch for example
msbuild Tempsolution.sln /t:rebuild
And for MSBuidlWorkspace, this code worked for me. We have to manually specify the analyzer to use by using compilation.WithAnalyzer(ImmutableArray<DiagnosticAnalyzer>);.
MSBuildLocator.RegisterDefaults();
var filePath = #"C:\Users\user\repos\ConsoleApp\ConsoleApp.sln";
var msbws = MSBuildWorkspace.Create();
var soln = await msbws.OpenSolutionAsync(filePath);
var errors = new List<Diagnostic>();
foreach (var proj in soln.Projects)
{
var analyzer = proj.AnalyzerReferences.Where(alz => alz.Display.ToLower() == "Your analyzer name").FirstOrDefault();
var compilation = await proj.GetCompilationAsync();
var compWithAnalyzer = compilation.WithAnalyzers(analyzer.GetAnalyzersForAllLanguages());
var res = compWithAnalyzer.GetAllDiagnosticsAsync().Result;
errors.AddRange(res.Where(r => r.Severity == DiagnosticSeverity.Error).ToList());
}
var count = errors.Count();
How to show Analyzer errors/warnings during msbuild in VS Dev Cmd &
using MSBuildWorkspace
Actually, these warnings are from Code analysis mechanism rather than MSBuild warnings(like MSBxxx). And I think the TestClass name not to be used is just a warning(yellow mark) not an error.
In VS IDE, its environment integrates the MSBuild tool(Developer Command Prompt for VS) and Code Analyzer. Because of this, you can get the warnings in VS IDE.
However, when you use Developer Command Prompt, which is essentially a separate compilation tool for MSBuild, it doesnot have an integrated code analyzer, so you don't have this type of warning except for MSBuild warnings and errors(MSBxxx). This is also the limitation of the tool. Warning by itself does not affect the entire program.
Test
You can test it by input this in an empty console project: int a=1;(It is a code analyzer warning) and I am sure that the warning can be showed in output window in VS IDE and will not be listed in Developer Command Prompt for VS.
Suggestion
As a suggestion, you can try to treat these warnings as errors and Code Analyzer passes these warnings to the msbuild and specifies them as errors so that you can get the error in DEV.
Add these in your xxx.csproj file:
<PropertyGroup>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
Although this approach breaks the build process, it is reliable and practical. And this method is very commonly used, generally used in the final production stage of the project, to exclude all errors and warnings for large projects, so as to prevent subsequent errors that may occur and be foolproof.
Then, you can use your code to build the project.

How to Use nativescript-autocomplete plugin with nativescript angular?

I am not able to make plugin work with angular project template .GitHub shows only code in native and XML .Sample plugin code works but unfortunately no angular support or help given. I am not able show on angular template.
relevant code i am using
detail.component.ts
registerElement("AutoComplete", () => require("nativescript-autocomplete").AutoComplete);
public list :Array = ['1','2','3','4','567'] ;
public itemTapped(args){
console.log("tapped");
}
detail.component.html
<AutoComplete items=""{{list}}"" itemTap="itemTapped($event)"> </AutoComplete>
i am getting exception on console while page loads and autocompletion doesnt work
this.items.forEach is not a function inside plugin code .that line is with definition of AutoComplete.prototype.itemsUpdate inside autocomplete.android.js plugin source
Debugging into plugin source it breaks at initialization time :
'AutoComplete.prototype.itemsUpdate = function (items) {
var arr = Array.create(java.lang.String, this.items.length);
this.items.forEach(function (item, index) {
arr[index] = item;
});
var ad = new android.widget.ArrayAdapter(app.android.context, android.R.layout.simple_list_item_1, arr);
this._android.setAdapter(ad);
};'
In detail.component.html
<AutoComplete [items]="list" (itemTap)="itemTapped($event)"> </AutoComplete>
in details.component.ts add
public list:any= ['1','2','3','4','567'] ;
itemTapped(ev){
//console.log(ev); your code
}
Issue in npm version. Clone the repository.
Replace all the files in node_modules/nativescript-autocomplete ,expect screenshot, demo folders and git related files. And try the solution

Skip single file from Minifying?

I'm trying to use ASP.Nets BundleTable to optomize some javascript files, but have run into a problem where a specific addon (jQuery-Timepicker) fails to work when the code has been minified. See here.
Bundle code is currently similar to:
// Add our commonBundle
var commonBundle= new Bundle("~/CommonJS" + culture.ToString());
// JQuery and related entries.
commonBundle.Include("~/Scripts/jquery-1.7.2.js");
commonBundle.Include("~/Scripts/jquery-ui-1.8.22.js");
commonBundle.Include("~/Scripts/jquery.cookie.js");
commonBundle.Include("~/Scripts/jquery-ui/jquery-ui-timepicker-addon.js"); // This is the one that does not work when bundled
// JS Transformer
commonBundle.Transforms.Add(new JsMinify());
BundleTable.Bundles.Add(commonBundle);
If I remove the jquery-ui-timepicker-addon.js file, then include it separate in my webpage, then it works properly. (Otherwise I get the Uncaught TypeError: undefined is not a function error).
I'm wondering if I can somehow setup my bundling code to skip minifying this one file (but still have it included in the bundle)? I've been looking around but have not come up with any solutions for doing so.
So the issue is that all the files are bundled together, and then the entire bundle is minimized. As a result you aren't going to easily be able to skip minification of just one file. Probably the best way to do this would be to create a new Transform that appended the contents of this file you want unminified. Then you would append this Transform to your registered ScriptBundle:
commonBundle.Transforms.Add(new AppendFileTransform(""~/Scripts/jquery-ui/jquery-ui-timepicker-addon.js""));
AppendFileTransform would simply append the contents of the file to the bundled response. You would no longer include the timepicker in the bundle explicitly, but instead this transform would be including it, and this would effectively give you the behavior you are looking since the JsMinify transform would run first and minify the bundle, and then you would add the file you want at the end unminified.
This can be solved better from the other direction - instead of trying to not minify a single file, add transforms for individual items instead.
First - create a class that implements IItemTransform and uses the same code to minify the given input:
public class JsItemMinify : System.Web.Optimization.IItemTransform
{
public string Process(string includedVirtualPath, string input)
{
var min = new Microsoft.Ajax.Utilities.Minifier();
var result = min.MinifyJavaScript(input);
if (min.ErrorList.Count > 0)
return "/*minification failed*/" + input;
return result;
}
}
Second - add this item transform to the individual files and remove the bundle transform:
var commonBundle= new Bundle("~/CommonJS");
// the first two includes will be minified
commonBundle.Include("~/Scripts/jquery-1.7.2.js", new JsItemMinify());
commonBundle.Include("~/Scripts/jquery-ui-1.8.22.js", new JsItemMinify());
// this one will not
commonBundle.Include("~/Scripts/jquery.cookie.js");
// Remove the default JsMinify bundle transform
commonBundle.Transforms.Clear();
BundleTable.Bundles.Add(commonBundle);
You cannot setup Bundle to skip minifying certain files and to minify rest of the files.
You could implement your own Bundle or Transform by overriding Bundle.ApplyTransform or JsMinify.Process methods, but you would need to take care not to break change-tracking of files, key generation, cache invalidation, etc... (or doing some ugly hack). It's not worth the effort.
I would keep separate js file, as you already mentioned.
This is just complete example based on Hao Kung's answer
var myBundle = new ScriptBundle("~/bundles/myBundle").Include(
"~/Scripts/script1.js",
"~/Scripts/script2.js",
);
myBundle.Transforms.Add(new AppendFileTransform("~/Scripts/excludedFile.min.js"));
bundles.Add(myBundle);
And here is example implementation of the AppendFileTransform:
public class AppendFileTransform : IBundleTransform
{
private readonly string _filePath;
public AppendFileTransform(string filePath)
{
_filePath = filePath;
}
public void Process(BundleContext context, BundleResponse response)
{
response.Content += File.ReadAllText(context.HttpContext.Server.MapPath(_filePath));
}
}

how to disable T4 template auto-run in visual studio (2012)?

I have some T4 templates in my project. Whenever I make changes and save the tt file, it auto update the generated files. This is a template that loops all tables in a database and generates about 100+ files. So visual studio hangs for a few seconds every time I save my template and this is annoying. Is there a way to disable to "auto-refresh" function and I can manually run the template through the context menu.
Thanks!
You could delete TextTemplatingFileGenerator under "Custom Tool" in the file's Properties while you are editing it, and then put it back when you are finished.
I had a similiar issue. I found a quick work around by creating a ttinclude file (actually this was already a standard include file containing utility functions for my templates) and including it in all of my T4 templates. Then I simply created a compiler error in the include file. Thus when the generator attempted to run it would simply fail on the compile. Then when I'm ready to actually generate, I get rid of the offending code and then generate.
e.g. To cause a failure:
<#+
#
#>
To disable the failure:
<#+
//#
#>
You can also use this trick in the T4 template itself if you just want to disable the one you're working on.
Hopefully future VS versions will allow you to simply disable the auto-transform.
Since the TT is always executed (still), I found a different way to control the output when the TT is executed.
/********SET THIS TO REGENERATE THE FILE (OR NOT) ********/
var _RegenerateFile = true;
/********COS VS ALWAYS REGENERATES ON SAVE ***************/
// Also, T4VSHostProcess.exe may lock files.
// Kill it from task manager if you get "cannot copy file in use by another process"
var _CurrentFolder = new FileInfo(Host.ResolvePath(Host.TemplateFile)).DirectoryName;
var _AssemblyLoadFolder = Path.Combine(_CurrentFolder, "bin\\Debug");
Directory.SetCurrentDirectory(_CurrentFolder);
Debug.WriteLine($"Using working folder {_CurrentFolder}");
if (_RegenerateFile == false)
{
Debug.WriteLine($"Not Regenerating File");
var existingFileName = Path.ChangeExtension(Host.TemplateFile, "cs");
var fileContent = File.ReadAllText(existingFileName);
return fileContent;
}
Debug.WriteLine($"Regenerating File"); //put the rest of your usual template
Another way (what I eventually settled on) is based on reading a conditional compilation symbol that sets a property on one of the the classes that is providing the data for the T4. This gives the benefit of skipping all that preparation (and IDE lag) unless you add the REGEN_CODE_FILES conditional compilation symbol. (I guess this could also be made into a new solution configuration too. yes, this does work and removes the need for the class change below)
An example of the class i am calling in the same assembly..
public class MetadataProvider
{
public bool RegenCodeFile { get; set; }
public MetadataProvider()
{
#if REGEN_CODE_FILES
RegenCodeFile = true; //try to get this to set the property
#endif
if (RegenCodeFile == false)
{
return;
}
//code that does some degree of preparation and c...
}
}
In the TT file...
var _MetaProvider = new MetadataProvider();
var _RegenerateFile = _MetaProvider.RegenCodeFile;
// T4VSHostProcess.exe may lock files.
// Kill it from task manager if you get "cannot copy file in use by another process"
var _CurrentFolder = new FileInfo(Host.ResolvePath(Host.TemplateFile)).DirectoryName;
var _AssemblyLoadFolder = Path.Combine(_CurrentFolder, "bin\\Debug");
Directory.SetCurrentDirectory(_CurrentFolder);
Debug.WriteLine($"Using working folder {_CurrentFolder}");
if (_RegenerateFile == false)
{
Debug.WriteLine($"Not Regenerating File");
var existingFileName = Path.ChangeExtension(Host.TemplateFile, "cs");
var fileContent = File.ReadAllText(existingFileName);
return fileContent;
}
Debug.WriteLine($"Regenerating File");

C#, ANTLR, ECMAScript grammar troubles

I'm trying to parse JavaScript (ECMASCript) with C#.
I found the following instruction on how to create new project:
http://www.antlr.org/wiki/pages/viewpage.action?pageId=557075
So I've downloaded ANTLRWorks, ANTLR v3, unpacked ANTLR, created a VS2010 project (.NET4), added references, checked and generated the grammar.
Then I recieved a lot of compilation error:
The type or namespace name 'AstParserRuleReturnScope' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'GrammarRule' could not be found (are you missing a using directive or an assembly reference?)
Stackoverlowed for them and got a solution: antlr c# errors when integrating into VS2008
So I've downloaded new runtime, overwrite the old one and recompiled the project and got
The name 'HIDDEN' does not exist in the current context d:\Workspace.1\ScriptParser\ScriptParser\TestLexer.cs
Ok, I've changed HIDDEN to Hidden as recommended at in the following conversation: [antlr-interest] How viable is the Csharp3 target? (more specific questions)
Now I'm trying to parse the input. I found a few examples and wrote the following code:
using Antlr.Runtime;
namespace ScriptParser
{
class Program
{
static void Main(string[] args)
{
var stream = new ANTLRStringStream("1+2");
var lexer = new TestLexer(stream);
var tokenStream = new CommonTokenStream(lexer);
var parser = new TestParser(tokenStream);
// what exactly should be here???
}
}
}
My goal is to parser JavaScript file with ANTLR but it seems that it will be the not as easy as I thought...
Update:
As suggested in Why are antlr3 c# parser methods private? I've modified the Test.g grammar by adding the "public" modified before the expr rule:
public expr : mexpr (PLUS^ mexpr)* SEMI!
;
and then regenerated the code, replaced HIDDEN to Hidden (again) and modified the code as follows:
var stream = new ANTLRStringStream("1+2");
var lexer = new TestLexer(stream);
var tokenStream = new CommonTokenStream(lexer);
var parser = new TestParser(tokenStream);
var result = parser.expr();
var tree = (CommonTree)result.Tree;
And not it is crashing on the line
root_0 = (object)adaptor.Nil();
in the following generated code
try { DebugEnterRule(GrammarFileName, "expr");
DebugLocation(7, 0);
try
{
// d:\\Workspace.1\\ScriptParser\\ScriptParser\\Test.g:7:13: ( mexpr ( PLUS ^ mexpr )* SEMI !)
DebugEnterAlt(1);
// d:\\Workspace.1\\ScriptParser\\ScriptParser\\Test.g:7:15: mexpr ( PLUS ^ mexpr )* SEMI !
{
root_0 = (object)adaptor.Nil();
DebugLocation(7, 15);
PushFollow(Follow._mexpr_in_expr31);
with the NullReferenceException message because the adapter is null.
I've resolved it by adding
parser.TreeAdaptor = new CommonTreeAdaptor();
Update 2:
So, finally I've started with my primary task: parse JavaScript.
ANTLR highlights the ECMAScript grammar by Chris Lambrou.
So I've generated lexer/parser and run it with the very simple JavaScript code:
var f = function () { };
and the parsing fails with the following output from tree.ToStringTree():
<error: var q = function () { };>
Your grammar rule says that there should be a semicolon at the end of the expression, but in you main function:
var stream = new ANTLRStringStream("1+2");
is missing a semicolon. Shouldn't it be "1+2;"?

Resources