Adding reference assemblies to Roslyn analyzer code fix unit tests - roslyn

I'm attempting to write a unit test to test a Roslyn analyzer code fix. Things have moved on since the introduction of analyzers and editing DiagnosticVerifier.Helper.cs is no longer the way ( https://www.productiverage.com/creating-a-c-sharp-roslyn-analyser-for-beginners-by-a-beginner )
My analyzer works on mvc ControllerBase derived types yet adding the name of the AspNetCore assemblies to the reference assemblies does not resolve the issue of my test not resolving the AspNetCore namespace includes in the test source code
var test = new VerifyCS.Test();
mytest.ReferenceAssemblies = test.ReferenceAssemblies.AddAssemblies( ImmutableArray.Create(new string[] { "Microsoft.AspNetCore.Mvc"}));
error CS0234: The type or namespace name 'AspNetCore' does not exist
in the namespace 'Microsoft' (are you missing an assembly reference?)
EDIT:
fixed, using:
mytest.ReferenceAssemblies = mytest.ReferenceAssemblies.WithPackages(ImmutableArray.Create(new PackageIdentity[] { new PackageIdentity("Microsoft.AspNetCore.Mvc.Core", "2.2.5") }));

You need to use the long syntax of VerifyCS.Test:
await new VerifyCS.Test
{
ReferenceAssemblies = referenceAssemblies,
TestState =
{
Sources = {test },
//ExpectedDiagnostics = {VerifyCS.Diagnostic().WithLocation(0).WithArguments("xxx")}
}, // FixedCode = "yyy", etc.
}.RunAsync();
You can add assemblies and nuget packages:
var referenceAssemblies = ReferenceAssemblies.Default
.AddPackages(ImmutableArray.Create(
new PackageIdentity("serilog", "2.10.0"),
new PackageIdentity("Othe.Package.Name", "1.2.0")
)
).AddAssemblies(
ImmutableArray.Create(
"Microsoft.Extensions.DependencyInjection.Abstractions",
"Microsoft.Extensions.Hosting",
"Microsoft.Extensions.Hosting.Abstractions")
);
BEWARE: the nuget packages are recovered only from the feeds specified in nuget.config, so, if you're using pacakages from an special feed, like your company's DevOps feed, you need to include it in this config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
....
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
<add key="myCompanyFeed" value="https://mycompanyfeed.pkgs.visualstudio.com/_packaging/MyCoNuget/nuget/v3/index.json" />
</packageSources>
<disabledPackageSources>
<clear />
</disabledPackageSources>
</configuration>
Removing the <clear/> is another option, but less portable.

Related

ClickOnce manual update still asks for update

I disabled update checking in Visual Studio by unchecking the publish property The application should check for updates.
My app checks for updates and the user has to option to decline to update.
The issue is when the user skips the update, the next time he starts the app the default ClickOnce update screen is presented again.
How do I make sure it never shows the default ClickOnce update dialog?
My update code:
private void CheckForUpdates()
{
if (!ApplicationDeployment.IsNetworkDeployed)
{
return;
}
var currentDeployment = ApplicationDeployment.CurrentDeployment;
UpdateCheckInfo info;
try
{
info = currentDeployment.CheckForDetailedUpdate();
}
catch (Exception e)
{
return;
}
if (!info.UpdateAvailable)
{
return;
}
var changelogDialog = new Changelog();
if (changelogDialog.ShowDialog() != true)
{
return;
}
currentDeployment.Update();
Exit();
}
This is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly xsi:schemaLocation="urn:schemas-microsoft-com:asm.v1 assembly.adaptive.xsd" manifestVersion="1.0" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns="urn:schemas-microsoft-com:asm.v2" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xrml="urn:mpeg:mpeg21:2003:01-REL-R-NS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:co.v1="urn:schemas-microsoft-com:clickonce.v1" xmlns:co.v2="urn:schemas-microsoft-com:clickonce.v2">
<assemblyIdentity name="test.ccpl.Desktop.application" version="1.0.0.89" publicKeyToken="7613da056444d824" language="en-CA" processorArchitecture="x86" xmlns="urn:schemas-microsoft-com:asm.v1" />
<description asmv2:publisher="test ccpl" co.v1:suiteName="test" asmv2:product="test ccpl" xmlns="urn:schemas-microsoft-com:asm.v1" />
<deployment install="true" mapFileExtensions="true" co.v1:createDesktopShortcut="true">
<deploymentProvider codebase="https://test-test.test.ca/Installers/test.ccpl.Desktop.application" />
</deployment>
<dependency>
<dependentAssembly dependencyType="install" codebase="Application Files\test.ccpl.Desktop_1_0_0_89\test.ccpl.Desktop.exe.manifest" size="58997">
<assemblyIdentity name="test.ccpl.Desktop.exe" version="1.0.0.89" publicKeyToken="7613da056444d824" language="en-CA" processorArchitecture="x86" type="win32" />
<hash>
<dsig:Transforms>
<dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<dsig:DigestValue>u36JKY4n1mmu2LZC3Ea5uRLheiM=</dsig:DigestValue>
</hash>
</dependentAssembly>
</dependency>
<compatibleFrameworks xmlns="urn:schemas-microsoft-com:clickonce.v2">
<framework targetVersion="4.7.2" profile="Full" supportedRuntime="4.0.30319" />
</compatibleFrameworks>
<publisherIdentity ...>
I think that everything you are seeing is by design.
As soon as you call currentDeployment.CheckForDetailedUpdate(), clickonce will store that update metadata in the registry. On next startup, clickonce will always look at this information to see if there is a pending deployment and if so, it will also determine if the user has skipped this newer version or not. If you want or not, this is by design.
However, if you really want to get rid of the clickonce Update dialog on startup, then there is an ugly solution available :-) Update: See below for a second workaround.
First, lets have a look at the registry and how everything works:
Navigate to this location:
HKEY_CURRENT_USER\Software\Classes\Software\Microsoft\Windows\CurrentVersion\Deployment\SideBySide\2.0\PackageMetadata\{2ec93463-b0c3-45e1-8364-327e96aea856}_{3f471841-eef2-47d6-89c0-d028f03a4ad5}\
You will see 3 sub keys for every clickonce application you have installed.
In my case the application is called WindowsApplication and the public key token is a619d47505395849. So the important key to look for starts with wind..tion_a619d47505395849_
You should see something similar to test..tion_7613da056444d824_xxxxxxxxxx on your side. Just iterate over the keys, look for the public key token and choose the shortest key.
Now comes the important part. Look at the value which name ends with !PendingDeployment. After calling the CheckForDetailedUpdate method, it should look like this:
This is why the Update Dialog is showing up.
And then just replace the value with this and you are done:
The Update Dialog will then not appear anymore. The user can manually check for an update within your application, accept or ignore it again and again.
You can test these steps manually to see if everything works as expected. Putting it in code should become something similar to this:
var changelogDialog = new Changelog();
if (changelogDialog.ShowDialog() != true)
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(#"Software\Classes\Software\Microsoft\Windows\CurrentVersion\Deployment\SideBySide\2.0\PackageMetadata\{2ec93463-b0c3-45e1-8364-327e96aea856}_{3f471841-eef2-47d6-89c0-d028f03a4ad5}");
var subkeyName = key.GetSubKeyNames().Where(x => x.Contains("7613da056444d824")).OrderBy(x => x.Length).First();
var subkey = key.OpenSubKey(subkeyName, true);
subkey.SetValue("{2ad613da-6fdb-4671-af9e-18ab2e4df4d8}!PendingDeployment", new byte[] { 00, 00 }, RegistryValueKind.Binary);
return;
}
UPDATE
Another Workaround:
Instead of calling the built-in function CheckForDetailedUpdate(), you can create your own "CheckForUpdate" method. That is not be a big deal:
private CustomUpdateCheckInfo CheckForUpdate()
{
var info = new CustomUpdateCheckInfo();
var currentVersion = ApplicationDeployment.CurrentDeployment.CurrentVersion;
var manifestUri = ApplicationDeployment.CurrentDeployment.UpdateLocation;
using (XmlTextReader reader = new XmlTextReader(manifestUri.AbsoluteUri))
{
var doc = XDocument.Load(reader);
var version = doc.Descendants().FirstOrDefault(n => n.Name.LocalName == "assemblyIdentity").Attribute("version").Value;
info.NewestVersion = version;
info.IsUpdateAvailable = currentVersion.ToString() != version;
}
return info;
}
It will compare the currently deployed version with the newest version in the manifest file and returns an instance of CustomUpdateCheckInfo:
public class CustomUpdateCheckInfo
{
public bool IsUpdateAvailable { get; set; }
public string NewestVersion { get; set; }
}

Models unit testing on Yii2

I'm trying to build Yii2 app through unit testing and i have some questions about it.
class UsersTest extends \Codeception\TestCase\Test
{
/**
* #var \UnitTester
*/
protected $users;
protected function _before()
{
$this->users = new \app\models\Users;
}
protected function _after()
{
}
// tests
public function testGeId()
{
}
}
When i try to run this test class i have fatal error message that Users class not found. What cause of the problem and how to solve it?
There is readme file in Yii2 tests folder which tell us to setup yii2-faker and yii2_basic_tests database. What are these two things and why i should to use them?
Thank you.
It was need to create application instance in tests/_bootstrap.php. It must be following code in that file:
require('/../vendor/autoload.php');
require('/../vendor/yiisoft/yii2/Yii.php');
$config = require('config/web.php');
(new yii\web\Application($config));
Possibly you
settings:
bootstrap: _bootstrap.php
in codeception.yml is wrong? This file include vendor/autoload.php and class names resolved
defined the auto loader in the phpunit xml configuration file
<?xml version="1.0" encoding="utf-8" ?>
<phpunit bootstrap="./vendor/autoload.php">
<testsuites>
<testsuite name="The project's test suite">
<directory>./tests</directory>
</testsuite>
</testsuites>
</phpunit>

How to run only selected test cases of a class in Selenium Automation testing project?

I have prepared a testng.xml file where I put number of test classes to run, for example:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<!-- REMOTE PROJECT -->
<suite name="Suite1" preserve-order="true">
<test name="Test1">
<parameter name="browsers" value="Chrome">
</parameter>
<classes>
<class name="com.project.live.Class1" />
<class name="com.project.live.Class2" />
<class name="com.project.live.Class3" />
...
...
...
<class name="com.project.live.Class...Nth" />
</classes>
</test>
<!-- Test -->
</suite> <!-- Suite -->
There are test cases in these classes with #Test Annotation, I want to run selected test cases only i.e. I will skip some tests of these classes.
1. One way to do this is put #Ignore Annotation and remove #Test Annotation from tests which I don't want to run (but that's lengthy work, very time consuming)
2. Another way is to use groupsbut again it is lengthy to select tests and put them in groups.
Query:Is there any optimal way to achieve this, may be some customized config file?
One way can be to use Iannotationtransformer.
Put another file which contains the list of cases to exclude (or include whichever list is shorter). Implement the transform method to check whether the current method falls in this exclude list, if yes, then set the enabled property to false for the annotation and it would be excluded.
Could you try IMethodInterceptor for this purpose?
Configure your test class with a listener implementing IMethodInterceptor and decide the tests to be run dynamically
A sample listener below.
public class MyTestListener implements IMethodInterceptor {
#Override
public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
List<IMethodInstance> methodlist = new ArrayList<IMethodInstance>();
// Read these flags from somewhere, system var / test context / file or
// where ever
Boolean shouldRunTest1 = Boolean.valueOf(context.getAttribute("SHOULD_RUN_TEST1")
.toString());
Boolean shouldRunTest2 = Boolean.valueOf(context.getAttribute("SHOULD_RUN_TEST2")
.toString());
for (IMethodInstance iMethodInstance : methods) {
// decide based on method name / group / priority / description or
// what ever
String methodName = iMethodInstance.getMethod().getMethodName();
if (iMethodInstance.getMethod().isTest()) {
if (shouldRunTest1 && methodName.equals("testCase1")) {
methodlist.add(iMethodInstance);
} else if (shouldRunTest2 && methodName.equals("testCase2")) {
methodlist.add(iMethodInstance);
}
}
}
// Here we return the test cases to be run
return methodlist;
}
see the below example ,when u wanted to run only "sanity3" ,you can comment the other methods(sanity0 ....sanity2) and run using xml file (right click and Run as ->testng)
Eg:
<run>
<!-- <include name="Sanity0"/>
<include name="Sanity1"/>
<include name="Sanity2"/> -->
<include name="Sanity3"/>

How to patch an attribute value with a Sitecore Include file

I need to create a Sitecore include patch file to add a string to the existing value attribute of the IgnoreUrlPrefixes setting in the web.config.
I have tried to overwriting the default ignored prefixes entirely with the following include file:
<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<settings>
<setting name="IgnoreUrlPrefixes">
<patch:attribute name="value">/foo/|/sitecore/default.aspx|/trace.axd|/webresource.axd|/sitecore/shell/Controls/Rich Text Editor/Telerik.Web.UI.DialogHandler.aspx|/sitecore/shell/applications/content manager/telerik.web.ui.dialoghandler.aspx|/sitecore/shell/Controls/Rich Text Editor/Telerik.Web.UI.SpellCheckHandler.axd|/Telerik.Web.UI.WebResource.axd|/sitecore/admin/upgrade/|/layouts/testing</patch:attribute>
</setting>
</settings>
</sitecore>
</configuration>
</settings>
Where /foo/ is the url prefix that I would like to add to the default prefixes. ShowConfig.aspx identifies that the modified configuration has not been applied.
Ideally I would like to be able to simply add /foo/ to whatever exists as the default IgnoreUrlPrefixes values. Does anyone know if this is possible and how to specify it in Sitecore patch syntax?
Good explanation of all possibilities of Sitecore include config files can be found in this John West blog post.
As you can find in the linked post:
patch:attribute: Define or replace the specified attribute.
It does not allow to "add /foo/ to whatever exists as the default IgnoreUrlPrefixes" attribute.
I recently ran into this same issue and it seems like Mark Ursino posted a blog on this particular issue:
http://firebreaksice.com/sitecore-patchable-ignore-lists/
In his example, he executes a custom pipeline after the default Sitecore one to update the value.
So instead, I’ve created a new pipeline processor that comes after the
built-in one (which will support the existing native IgnoreUrlPrefixes
setting) and will allow you to add each path via its own XML config
node. The advantage here is you can patch and continue to patch on
without needing to copy the existing values.
Sample patch file:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<httpRequestBegin>
<processor type="Sitecore.PatchableIgnoreList.ProcessPatchedIgnores, Sitecore.PatchableIgnoreList"
patch:after="processor[#type='Sitecore.Pipelines.HttpRequest.IgnoreList, Sitecore.Kernel']">
<Paths hint="list:AddPaths">
<foo>/foo</foo>
<bar>/bar</bar>
</Paths>
</processor>
</httpRequestBegin>
</pipelines>
</sitecore>
</configuration>
Source code for the pipeline processor, from the blog:
using Sitecore.Collections;
using Sitecore.Pipelines.HttpRequest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Sitecore.PatchableIgnoreList
{
public class ProcessPatchedIgnores : HttpRequestProcessor
{
private List<string> _paths = new List<string>();
public override void Process(HttpRequestArgs args)
{
string filePath = args.Url.FilePath;
foreach (string path in _paths)
{
if (filePath.StartsWith(path, StringComparison.OrdinalIgnoreCase))
{
args.AbortPipeline();
return;
}
}
}
public void AddPaths(string path)
{
if (!string.IsNullOrEmpty(path) && !_paths.Contains(path))
{
_paths.Add(path);
}
}
}
}

how replace XmlGregorianCalendar by Date?

I have to expose an ejb service layer via jax-ws .
I have generated the web service using jax-ws and wsimport but I'm stopped by a strange things ; Date are being mapped to XmlGregorianCalendar .
Is it possible to use classic java Date instead ?
Can you show me the right way to proceed ?
Thanks .
Edit:
this the binding file i used :
thanks , I modified slightly your xml and attached it with netbeans to the client's webservice and it worked . This the binding I used :
<jaxws:bindings node="wsdl:definitions/wsdl:types/xsd:schema"
xmlns:jaxws="http://java.sun.com/xml/ns/jaxws"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" wsdlLocation="../wsdl/localhost_8080/web_test/Testor.wsdl" >
<jaxb:globalBindings>
<jaxb:javaType name="java.util.Date"
xmlType="xsd:dateTime"
parseMethod="lol.XsdDateTimeConverter.unmarshal"
printMethod="lol.XsdDateTimeConverter.marshalDateTime"
/><jaxb:javaType
name="java.util.Date"
xmlType="xsd:date"
parseMethod="lol.XsdDateTimeConverter.unmarshal"
printMethod="lol.XsdDateTimeConverter.marshalDate"
/>
</jaxb:globalBindings>
</jaxws:bindings>
Not tested, but should work. First create such class:
import javax.xml.bind.DatatypeConverter;
public class XsdDateTimeConverter {
public static Date unmarshal(String dateTime) {
return DatatypeConverter.parseDate(dateTime).getTime();
}
public static String marshalDate(Date date) {
final GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
return DatatypeConverter.printDate(calendar);
}
public static String marshalDateTime(Date dateTime) {
final GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(dateTime);
return DatatypeConverter.printDateTime(calendar);
}
}
Then add this to custom xjb file:
<javaType
name="java.util.Date"
xmlType="xs:dateTime"
parseMethod="XsdDateTimeConverter.unmarshal"
printMethod="XsdDateTimeConverter.marshalDateTime"
/>
<javaType
name="java.util.Date"
xmlType="xs:date"
parseMethod="XsdDateTimeConverter.unmarshal"
printMethod="XsdDateTimeConverter.marshalDate"
/>
</globalBindings>
Not tested, but should work. Based on my answer here: JAX-WS and Joda-Time?
Thanks Tomasz. The above solution works.
But wsimport also adds its set of Adapters like Adapter1.java and Adapter2.java with its package org.w3._2001.xmlschema, which really doesnot match my own package structure.
I found a way to change this package name using another jaxb binding. Actually, I searched for this a lot and could not find this easily, so I am adding it here for anyone looking for the same.
Add the following binding in the wsimport using '-b binding.xml'. Note that wsimport can work with multiple binding files.
binding.xml content below:
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3.org/2001/XMLSchema"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
jaxb:version="2.0">
<annotation><appinfo>
<jaxb:schemaBindings>
<jaxb:package name="com.abc.xyz.utils"/>
</jaxb:schemaBindings>
</appinfo></annotation>
</schema>