I am having a problem using Visual Studio data driven testing. I have tried to deconstruct this to the simplest example.
I am using Visual Studio 2012. I create a new unit test project.
I am referencing system data.
My code looks like this:
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
[DeploymentItem(#"OrderService.csv")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "OrderService.csv", "OrderService#csv", DataAccessMethod.Sequential)]
[TestMethod]
public void TestMethod1()
{
try
{
Debug.WriteLine(TestContext.DataRow["ID"]);
}
catch (Exception ex)
{
Assert.Fail();
}
}
public TestContext TestContext { get; set; }
}
}
I have a very small csv file that I have set the Build Options to to 'Content' and 'Copy Always'. I have added a .testsettings file to the solution, and set enable deployment, and added the csv file.
I have tried this with and without |DataDirectory|, and with/without a full path specified (the same path that I get with Environment.CurrentDirectory). I've tried variations of "../" and "../../" just in case. Right now the csv is at the project root level, same as the .cs test code file.
I have tried variations with xml as well as csv.
TestContext is not null, but DataRow always is.
I have not gotten this to work despite a lot of fiddling with it. I'm not sure what I'm doing wrong.
Does mstest create a log anywhere that would tell me if it is failing to find the csv file, or what specific error might be causing DataRow to fail to populate?
I have tried the following csv files:
ID
1
2
3
4
and
ID, Whatever
1,0
2,1
3,2
4,3
So far, no dice.
I am using ReSharper, could it be interfering in some way?
Updated
I have it mostly working now! I am able to use XML, but when I use CSV my column, which is named ID comes back as ID
Not sure why. I've checked the actual file of course, and no weird characters are present.
For anyone having a similar problem, I turned off Just My Code and enabled Net Framework source stepping, etc. so that I could get more detailed debug information. This allowed me to determine that ReSharper was causing me problems. I disabled resharper and modified my attributes like this:
[DeploymentItem("UnitTestProject1\\OrderService.csv")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\bin\\Debug\\OrderService.csv", "OrderService#csv", DataAccessMethod.Sequential)]
And it worked (except as noted). I am still suspicious of the "bin\debug" in my path, but I'm just happy my DataRow is no longer null.
Thanks!
Any ideas?
I was struggling with a similar problem today when trying to make data-driven tests work with CSV input file. The name of the first column had some garbage at the beggining of it, i.e. ID instead of just ID.
It turned out it was an encoding issue. The CSV file was saved in UTF-8 which adds a byte order mark at the beginning, obviously confusing the parser. Once I saved the file in ANSI encoding, it worked as expected.
I know it's an old question, but this information might help someone else ending up on this page.
Have you tried adding it through the properties window?
Go to Test menu -> Windows -> Test View -> the tests will load up.
Click on the test to alter i.e. TestMethod1 and press F4 (properties).
Look for 'Data Source' and click the ellipses next to it
It will walk you through a wizard that sets up the attributes properly for the TestMethod
You have the deployment part set up properly, which is normally the big stumbling block.
You also don't have to set the build action to Copy Always as the deployment does this for you. This option is used if you include items like .xml files you use for configs, or icons/images as part of your project.
Update 1:
Also try this tutorial on MSDN.
Update 2:
Try this post, involving ProcMon
I see that you said you tried putting the CSV itself into the testsettings file, but have you tried just putting in the directory?
<Deployment>
<DeploymentItem filename="Test\Data\" />
</Deployment>
Then your DataSource line will look something like this:
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\YOURCSV.csv", "YOURCSV#csv", DataAccessMethod.Sequential)]
If you do it this way, you don't need to specify the DeploymentItem line.
Our folder structure looks like this: Trunk\Test\Test\Data
We include: Test\Data in the deployment
We then access Test\Data via the |DataDirectory|\
All CSVs live within the \Data folder
Related
I am trying to create a simple flow using the BIML <ScriptComponentProject> tag, but it does not work for me!
if I create the data flow manually, then it works perfectly fine!
my data flow has: SRC > SCRIPT-COMPONENT > TGT
the only logic that I have added is to calculate a row-number for each incoming row (keeping the logic absolutely simple for now)
when the manual solution is executed:
the sequential row-number is stored in the TGT table (test_np_02)
Great!
however, when I try to create absolutely the same package using the attached BIML, I get the following errors:
SSIS Output log:
Error 0 The namespace '<global namespace>' already contains a definition for 'Input0Buffer'. ...\Designer\BufferWrapper.cs 14 14
Error 0 The namespace '<global namespace>' already contains a definition for 'UserComponent'. ...\Designer\ComponentWrapper.cs 12 14
Error 0 The namespace '<global namespace>' already contains a definition for 'Connections'. ...\Designer\ComponentWrapper.cs 49 14
Error 0 The namespace '<global namespace>' already contains a definition for 'Variables'. ...\Designer\ComponentWrapper.cs 60 14
EmitSsis. Internal Compiler Error: Workflow EmitSsis contains fatal errors. Phase execution halted.
I am unsure what is going wrong when I try to create the PKG using BIML:
these errors never popped up when I created the package manually (with the same code)
I copy-pasted the important C# files from the manual solution into the BIML
Questions / Ideas:
is it something to do with the GUID that has to be used for ProjectCoreName, AssemblyProduct and AssemblyTitle?
is this automatically generated each time the BIML is expanded?
if so, how can I create a GUID in the BIML itself for these items .. so that it works directly after expansion?
is it something to do with the sequence in which I have to create the .cs files in the BIML, within the <Files> tag?
I currently assume that actual sequence of the <File> items within the <Files> tag is not relevant for BIML
could it be that I have to generate "Resources.resx/Resources.Designer.cs" and "Settings.settings/Settings.Designer.cs" as well in the BIML?
is it really important to have the "#region Namespaces" section in each .cs file?
I removed that from the manual soln .. that still worked fine !
Pls help.
Notes:
I am using SSDT 2015 and Varigence BIMLExpress 2017 (Build 5.0.61915.0)
I am aware that this could very easily be done using ROW_NUMBER() within SQLServer in the SRC itself, but:
I am using OleDbSource in the attached example just to keep it simple
finally, I will have to generate hundreds of code PKGs with BIML, which will have the SRC as a flat file, and not OleDB.
and obviously, I would love to have my generated ScriptComponents work immediately after expansion .. without any further manual interventions :)
Thanx,
NP
BIML file: https://drive.google.com/file/d/10O3aSL5IO34ULS44wl7IX4LUmPH_pI6V/view?usp=sharing
The error will disappear if you wrap your classes in a custom namespace.
namespace SomeNamespace {
public class UserComponent: ScriptComponent
{
...
}
public class Connections
{
...
}
public class Variables
{
...
}
}
namespace SomeNamespace {
public class Input0Buffer: ScriptBuffer
{
...
}
}
Also one remark about (dynamically) creating multiple packages from this Biml file: You will have to assign a dynamic namespace name like so:
namespace <#=variableContainingNamespaceName#> {
...
}
About your remarks:
The issue is not related to the ProjectCoreName, but I fear that you may run into issues if you reuse the same ProjectCoreName for multiple packages generated from the same biml (without having actually tested it)
No
Not necessary
No, the section is not necessarily required.
I'm using the roslyn API to write a DiagnosticAnalyzer and CodeFix.
After I have collected all strings and string-interpolations, I want to write all of them to a file but I am not sure how to do this the best way.
Of course I can always simply do a File.WriteAllText(...) but I'd like to expose more control to the user.
I'm also not sure about how to best trigger the generation of this file, so my questions are:
I do not want to hard-code the filename, what would be the best way to expose this setting to the user of the code-analyzer? A config file? If so, how would I access that? ie: How do I know the directory?
If one string is missing from the file, I'd like to to suggest a code fix like "Project contains changed or new strings, regenerate string file". Is this the best way to do this? Or is it possible to add a button or something to visual studio?
I'm calling the devenv.com executable from the commandline to trigger builds, is there a way to force my code-fix to run either while building, or before/after? Or would I have to "manually" load the solution with roslyn and execute my codefix?
I've just completed a project on this. There are a few things that you will need to do / know.
You will probably need to switch you're portable class library to a class library. otherwise you will have trouble calling the File.WriteAllText()
You can see how to Convert a portable class library to a regular here
This will potentially not appropriately work for when trying to apply all changes to document/project/solution. When Calling from a document/project/solution, the changes are precalcuated and applied in a preview window. If you cancel, an undo action is triggered to undo all changes, if you write to a file during this time, and do not register an undo action you will not undo the changes to the file.
I've opened a bug with roslyn but you can handle instances by override the preview you can see how to do so here
And one more final thing you may need to know is how to access the Solution from the analyzer which, Currently there is a hack I've written to do so here
As Tamas said you can use additional files you can see how to do so here
You can use additional files, but I know on the version I'm using resource files, are not marked as additional files by default they are embeddedResources.
So, for my users to not have to manually mark the resource as additonalFiles I wrote a function to get out the Designer.cs files associated with resource files from the csproj file using xDoc you can use it as an example if you choose to parse the csproj file:
protected List<string> GetEmbeddedResourceResxDocumentPaths(Project project)
{
XDocument xmldoc = XDocument.Load(project.FilePath);
XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
var resxFiles = new List<string>();
foreach (var resource in xmldoc.Descendants(msbuild + "EmbeddedResource"))
{
string includePath = resource.Attribute("Include").Value;
var includeExtension = Path.GetExtension(includePath);
if (0 == string.Compare(includeExtension, RESX_FILE_EXTENSION, StringComparison.OrdinalIgnoreCase))
{
var outputTag = resource.Elements(msbuild + LAST_GENERATED_TAG).FirstOrDefault();
if (null != outputTag)
{
resxFiles.Add(outputTag.Value);
}
}
}
return resxFiles;
}
For config files you can use the AdditionalFiles msbuild property, which is passed to the analyzers through the context. See here.
After deploying a new version of a website the browser loads everything from its cache from the old webpage until a hard, force refresh is done.
In ASP.NET MVC if the file becomes in Bundle, it handled by Optimization framework. a version added to your file link, and if a change occurs in your bundle's file a new token generate. follow below code :
for example, js file name is: datatables
when you put it in a bundle with the same name, you will see the
datatables?v=anY9_bo7KitrGnXQr8ITP3ylmhQe9NDzSjgLpLQWQFE1
as a file name.
change datatables and watch again the name of the file in the browser, surely it will change:
datatables?v=r8yhQBxKyDgrOGyqr1ndtdG92Ije09nqTY7yogrOSTk1
But there's two questions:
What we can do if our file wasn't in Bundle?
Is a way to force the browser to refresh cache?
we have one solution with some different way for implementation. we use above solution for it.
datatables?v=1
we can handle the version of the file, it's mean that every time that we change our file, change the version of it too. but it's not a suitable way.
another way used Guide, it wasn't suitable too, because each time it fetches the file and doesn't use from the browser cache.
datatables?v=Guid.NewGuid()
The last way that is the best Way is :
when file change occur , change version too. check follow code :
<script src="~/scripts/main.js?v=#File.GetLastWriteTime(Server.MapPath("/scripts/main.js")).ToString("yyyyMMddHHmmss")"></script>
by this way, when you change the file, LastWriteTime change too, so the version of the file will change and in the next when you open the browser, it detects a new file and fetch it.
Assuming you cannot use bundling for some reason, the solution suggested by the original poster is good enough, however it's better to put the logic inside a helper method.
It makes the code testable, it helps to change the logic without changing .cshtml , and also helps to not repeat the filename twice. Then you can have have a much cleaner code:
<script src="#Url.ContentWithVersion("~/scripts/main.js")"></script>
To do so, you can add ContentWithVersion extension method to the existing UrlHelper:
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
public static class UrlHelperExtensions
{
public static string ContentWithVersion(this UrlHelper urlHelper, string path)
{
if (urlHelper == null)
throw new ArgumentNullException(nameof(urlHelper));
var result = urlHelper.Content(path);
var file = HttpContext.Current.Server.MapPath(path);
if (File.Exists(file))
result += $"?v={File.GetLastWriteTime(file).ToString("yyyyMMddHHmmss")}";
return result;
}
}
Is there a way to find out the assembly name at design-time (i.e. not using reflection or runtime APIs such as System.Reflection.Assembly.GetEntryAssembly) from within Visual Studio?
The scenario requires a tool to get the assembly name that a Visual Studio project will eventually compile into.
This is like parsing the AssemblyName property of the .csproj - I am wondering if there are any APIs that can give this information reliably.
Please do not respond back with runtime APIs that use reflection - there is no assembly file present at the time I need the assembly name - just the metadata of the assembly in the csproj file.
if you are calling the tool via a post/pre-build event, this data is very easy to access.
Just go to the "project properties->Build Events" tab, then select either "edit pre-build" or "edit post-build", depending on when you want the tool to run. This should bring up an edit window with the ever helpful "Macros >>" button. Press this and you will be given a heap of macros to use and should be pretty much everything you need.
The "API" you could use is LINQ to XML after all the .csproj file is just xml. (and you can get the location of the .csproj file if you need from the solution file which for some reason is not XML but can be easily parsed)
You can use "TargetName" available in Macros for Post-build events. It will give you the assembly name for your project.
After a quick run through MSDN I found this article which might be a good start for some further research:
Accessing Project Type Specific Project, Project Item, and Configuration Properties
I think you will need to write some regular expression that will give you the value of "AssemblyTitle" attribute in AssemblyInfo.cs file.
Something like this:
public class Assembly
{
public static string GetTitle (string fileFullName) {
var contents = File.ReadAllText (fileFullName); //may raise exception if file doesn't exist
//regex string is: AssemblyTitle\x20*\(\x20*"(?<Title>.*)"\x20*\)
//loading from settings because it is annoying to type it in editor
var reg = new Regex (Settings.Default.Expression);
var match = reg.Match (contents);
var titleGroup = match.Groups["Title"];
return (match.Success && titleGroup.Success) ? titleGroup.Value : String.Empty;
}
}
I'm new to code contracts. I downloaded the latest build of code contract project (1.4.40314.1) and started to implement it in my project. When i enabled 'Runtume Checking' through Code Contracts Tab in VS2010, i got this Error
Error 1 The command ""C:\Program Files (x86)\Microsoft\Contracts\Bin\ccrewrite" "#Application1ccrewrite.rsp"" exited with code -1.
everytime i build the project. Plz help.
Now it's a major problem for me.
Every project using code contracts is showing same error in VS2010 Errors window and 'Application1ccrewrite.rsp' not found in output window, but it is there.
I tried out everything. I installed both versions (Pro, Std) but the problem persist. Plz help !
I had this problem as well. In my case the problem was that ccrewrite cannot work with files in a network folder but requires the project to be on your local hard disk.
I had this problem. The Assembly name and Default namespace of the class library that causes the problem had the same name as an existing DLL in the destination folder. I had been refactoring my code and whilst the namespaces in the CS files had all be changed to namespace2 the default namespace in the properties file was still namespace1
When I corrected this the files all built successfully...
Sometimes you can get this when your solution path is too long, especially with many projects.
Try moving to c:\temp and building it, it might fix it (although of course, this might not be a solution if you need it in the folder it currently is).
This bug I noticed in earlier CC versions and may now be fixed.
I don't know if you had the same problem as me, but I also saw this error. In my case, I had a method with a switch statement, and depending on the branch taken, different requirements applied:
static ITransaction CreateTransaction(
String transType,
MyType1 parm1,
/* Other params unimportant to this example */
String parm5)
{
switch (transType) {
case Transaction.Type.SOME_TRANSFER:
Contract.Requires<ArgumentNullException>(parm1.Account != null, "Account cannot be null.");
Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(parm5), "parm5 cannot be null or empty.");
// Create instance
return someInst;
case Transaction.Type.SOME_OTHER_TRANSFER:
Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(parm1.Type), "Type cannot be null or empty.");
Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(parm1.Number), "Number cannot be null or empty.");
// Create instance
return someInst;
/* Other cases */
default:
throw new ApplicationException("Invalid or unknown transaction type provided.");
}
}
This was giving me the error you noted in the Errors List when I tried to build. In the output window, I was getting this:
EXEC : Reference Assembly Generator
warning : Something is wrong with
contract number 1 in the method
'TerraCognita.LoanExpress.Domain.Loan.CreateLoanTransaction'
AsmMeta failed with uncaught
exception: Operation is not valid due
to the current state of the object.
I pushed each branch into a method of its own, making Contract.Requires the first lines of code in each method, and I no longer had a compilation problem. It appears that Contract.Requires must be the first lines of code in a method - which makes sense, since they are intended to be used to define pre-conditions.
Hope this helps.
The solution is to put the pre and pos conditions in the first lines. The ccrewrite does not accept that pre and post conditions are below command lines.