Create file template with generic macro - resharper

this is my template code:
using System;
using System.Runtime.Serialization;
using Nethos.Ferramentas.AtributosValidacao.Numeros;
using Nethos.Ferramentas.AtributosValidacao.Textos;
$HEADER$namespace $NAMESPACE$
{
/// <summary>
/// Classe responsável pela persistência dos dados.
/// Tabela: $CLASS$s (PK: Id)
/// </summary>
[DataContract]
[KnownType(typeof(NHibernate.Collection.Generic.PersistentGenericBag< $CLASS$ >))]
[KnownType(typeof(NHibernate.Collection.PersistentBag))]
[Serializable]
public class $CLASS$
{
$END$
}
}
but in the line "[KnownType(typeof(NHibernate.Collection.Generic.PersistentGenericBag< $CLASS$ >))]" not appear name of the class, just the letter "a"... what's the problem with my code template?

I suspect this is an issue that the original 8.0 release of ReSharper has with certain plugins, under certain conditions. If you open Visual Studio by double clicking a solution file, the plugin would get initialised too late, and cause exceptions (you can verify by running "devenv.exe /ReSharper.Internal" and look for exceptions). The exceptions can interfere with various parts of ReSharper, unfortunately, macros is one that I've seen.
This has been fixed with ReSharper 8.0.1. Please can you update and try again?

Related

How to access Custom field,which is defined in Construction feature package- Acumatica

By reading my question, you might think its very easy, but i request everyone to try to access a custom field defined in the construction feature package.
I want to access "Type" field in Project screen's Task Tab in details
UsrType is a custom field defined in Construction features package. In that package, file has been converted into dll. I tried to access that field like we usually do in customization.
but i got error
Type or Namespace "PMTaskExt" could not be found
I even tried this
I got error
UsrType Doesn't exist in PMTask
There is also same problem with UsrSubcontractNbr field in APTran. Not Only these fields, there are many such field to be accessed.
How can we access such fields?
From looking at PX.Objects.CN.dll it would be in the PX.Objects.CN.ProjectAccounting.PM.CacheExtensions namespace as PmTaskExt
Used the latest 19R2 Construction project "ConstructionFeatures_19_205_4_1_157"
Decompiled the customization dll (used DotPeek) I searched for PMTask:
Copied text:
using PX.Data;
using PX.Data.BQL;
using PX.Objects.CN.ProjectAccounting.PM.Descriptor;
using PX.Objects.CS;
using PX.Objects.PM;
namespace PX.Objects.CN.ProjectAccounting.PM.CacheExtensions
{
public sealed class PmTaskExt : PXCacheExtension<PMTask>
{
[PXDBString(30)]
[PXDefault]
[PXUIField(DisplayName = "Type", Required = true)]
[ProjectTaskType.List]
public string UsrType { get; set; }
public static bool IsActive()
{
return PXAccess.FeatureInstalled<FeaturesSet.construction>();
}
public abstract class usrType : BqlType<IBqlString, string>.Field<PmTaskExt.usrType>
{
}
}
}
Something like this should work:
var cnExt = PXCache<PX.Objects.PM.PMTask>.GetExtension<PX.Objects.CN.ProjectAccounting.PM.CacheExtensions.PmTaskExt>((PX.Objects.PM.PMTask)e.Row);
Do note the .Net version of PX.Objects.CN.dll is using 4.8 in case that causes any issues with version compatibility in visual studio if your solution is compiled on the same version of Acumatica for 19R2 which is 4.7.1

Handling standard commands in custom editor

I have created a Visual Studio extension that provider syntax highlighting by implementing IClassifierProvider. I would like to add additional features such as support for the standard Edit.CommentSelection and Edit.FormatDocument commands, but I have no idea how to do that. All the documentation I can find is about adding new commands, but the commands I want to handle already exist.
How can I handle these commands?
I considering the specific Comment Selection and Uncomment Selection commands you refer to as special cases, because I'm working on a Commenter Service specifically intended to support these two actions. The service is being developed on GitHub and will be released via NuGet when it is ready. I'll start with a description of this service, and follow with some general information about implementing support for specific commands, including the Format Document command.
I would like to release the library and its dependencies this week, but the restriction that the Commenter Interfaces assembly be an immutable assembly demands more testing than is generally given to a library prior to its initial release. Fortunately the only thing in this particular assembly is two interfaces is the Tvl.VisualStudio.Text.Commenter.Interfaces namespace.
Using the Commenter Service
Source: Commenter Service (Tunnel Vision Labs' Base Extensions Library for Visual Studio)
This services allows extension developers to easily support the Comment and Uncomment commands for new languages in Visual Studio.
Providing a Standard Commenter
The easiest way to provide commenting features is to use the standard Commenter implementation of the ICommenter interface. The following steps show how to create an instance of Commenter and provide it to the Commenter Service by exporting an instance of ICommenterProvider.
Create a new class derived from ICommenterProvider. This class is exported using the MEF ExportAttribute for one or more specific content types using the ContentTypeAttribute. The commenter in the example supports C++-style line and block comments, for the SimpleC content type.
[Export(typeof(ICommenterProvider))]
[ContentType("SimpleC")]
public sealed class SimpleCCommenterProvider : ICommenterProvider
{
public ICommenter GetCommenter(ITextView textView)
{
// TODO: provide a commenter
throw new NotImplementedException();
}
}
Define the comment format(s) the commenter will support.
private static readonly LineCommentFormat LineCommentFormat =
new LineCommentFormat("//");
private static readonly BlockCommentFormat BlockCommentFormat =
new BlockCommentFormat("/*", "*/");
Implement the GetCommenter(ITextView) method by returning an instance of Commenter. The ITextUndoHistoryRegistry service is imported in order for Commenter to correctly support the Undo and Redo commands. The following code is the complete implementation of ICommenterProvider required to support the Comment and Uncomment commands for a simple language.
[Export(typeof(ICommenterProvider))]
[ContentType("SimpleC")]
public sealed class SimpleCCommenterProvider : ICommenterProvider
{
private static readonly LineCommentFormat LineCommentFormat =
new LineCommentFormat("//");
private static readonly BlockCommentFormat BlockCommentFormat =
new BlockCommentFormat("/*", "*/");
[Import]
private ITextUndoHistoryRegistry TextUndoHistoryRegistry
{
get;
set;
}
public ICommenter GetCommenter(ITextView textView)
{
Func<Commenter> factory =
() => new Commenter(textView, TextUndoHistoryRegistry, LineCommentFormat, BlockCommentFormat);
return textView.Properties.GetOrCreateSingletonProperty<Commenter>(factory);
}
}
Command Handling in Visual Studio
The following are general steps for handling commands in Visual Studio. Keep in mind that the implementation details are quite complicated; I've created some abstract base classes to simplify specific implementations. After this overview, I will point to both those and a concrete example of their use for you to reference.
Create a class which implements IOleCommandTarget. The QueryStatus method should check for the specific commands handled by your command target and return the appropriate status flags. The Exec method should be implemented to execute the commands.
Register the command target with a specific text view by calling IVsTextView.AddCommandFilter. If you are working with an MEF-based extension, you can obtain the IVsTextView by either exporting an instance of IVsTextViewCreationListener, or by importing the IVsEditorAdaptersFactoryService component and using the GetViewAdapter method to obtain an IVsTextView from an instance of ITextView.
Here are some specific implementations of the interfaces described here:
CommandFilter: This class implements the basic requirements for IOleCommandTarget
TextViewCommandFilter: This class implements additional functionality to simplify the attachment of a command filter to a text view
CommenterFilter: This class is a concrete implementation of a command filter used by the Commenter Service implementation to handle the Comment Selection and Uncomment Selection commands

How to create a ReSharper 8.X Custom Macro that can fetch and process the containing type name

ReSharper 8.X ships with a macro that fetches the "Containing Type Name", but what I want to do is manipulate that name. I'm using this in a Visual Studio 2013 Web API project, and I want a template that takes the class name and builds the URL that has to be called. So, for example, suppose I have this:
public class AnnouncementController : ApiController
{
//Want to put a template here!
[HttpGet]
public HttpResponseMessage GetActiveAnnouncements()
{
/// ...
}
}
now my ReSharper template will look something like this:
/// This sample shows how to call the <see cref="$METHOD$"/> method of controller $CLASS$ using the Web API.
/// https://myurl.mydomain.com/api/$CONTROLLER$/$METHOD$
$Controller$, by convention, is the class name minus the letters 'Controller'. This is because ASP.NET MVC Web API projects expect classes derived from ApiController to end with the string 'Controller',
Since this class is AnnouncementController, the template should output
https://myurl.mydomain.com/api/Announcement/GetActiveAnnouncements
Resharper's Built-In Macros can give me some of what I need, but I want to write a custom macro that fetches the containing type name and chops "Controller" off of it. I would like to do that directly, without storing the containing type name in another parameter.
Also, how do I install this custom macro? I've Googled around, and all I found was a lot of dead links and old walkthroughs written for ReSharper version 7 and below that do NOT work with ReSharper 8.x
After a lot of fighting, here is my solution.
[MacroImplementation(Definition = typeof (ControllerNameMacroDefinition))]
public class ControllerNameMacroImplementation : SimpleMacroImplementation
{
public ControllerNameMacroImplementation([Optional] IReadOnlyCollection<IMacroParameterValueNew> arguments)
{
}
public override HotspotItems GetLookupItems(IHotspotContext context)
{
var ret = "CONTROLLER";
var fileName = GetFileName(context);
if (!fileName.IsNullOrEmpty())
{
//Replace "Controller.cs" in two separate steps in case the extension is absent
ret = fileName.Replace("Controller", "").Replace(".cs", "");
}
return MacroUtil.SimpleEvaluateResult(ret);
}
/// <summary>
/// Returns the filename of the current hotspot context
/// </summary>
private string GetFileName(IHotspotContext context)
{
var psiSourceFile = context.ExpressionRange.Document.GetPsiSourceFile(context.SessionContext.Solution);
return psiSourceFile == null ? string.Empty : psiSourceFile.Name;
}
}
I wanted to do exactly this, but for JavaScript Jasmine tests -- SomethingViewModel.js, with a fixture of SomethingViewModelFixture.js, but wanted to be able to refer to SomethingViewModel in the file. A few slight modifications to the above made it possible.
Unfortunately, there's a ton more things you need to do in order to get your plugin to actually install. Here's a list. I hope it's comprehensive.
NuGet package install JetBrains.ReSharper.SDK, make sure you have the correct version installed!
Copy your Class Library DLL to C:\Users\<you>\AppData\Local\JetBrains\ReSharper\<version>\plugins\<your plugin name>, creating the plugins directory if needed.
You need the plugin Annotations in your AssemblyInfo.cs file:
[assembly: PluginTitle("Your extensions for ReSharper")]
[assembly: PluginDescription("Some description")] -- this is displayed in ReSharper->Options->Plugins
[assembly: PluginVendor("You")]
You need a class in your project that defines the MacroDefinition, as well as the above MacroImplementation
[MacroDefinition("MyNamespace.MyClassName", ShortDescription = "A short description of what it does.", LongDescription = "A long description of what it does.")]
"ShortDescription" - this is displayed in the "Choose Macro" dialog list.
"LongDescription" you'd think this would be in the "Choose Macro" description, but it isn't.
I just added this annotation to the above file.
The file you add the MacroDefinition to needs to implement IMacroDefinition, which has a method (GetPlaceholder) and a property (Parameters) on it. The former can return any string ("a") and the latter can return an empty array.
You can ignore the WiX/NuGet stuff if you want. Just for a local install.
In VS, the ReSharper->Options->Plugins section has some troubleshooting details on why your plugin might not be loading.
Good luck!

how to generate code in second UImap from existing recording

I am new to codedUI and for a start I am reading a lot about what should be a best practice.
I have read that if you are using complex application that is advisable to use multiple UImaps. Although I can not see a benefit at the moment I have created small project with two UImaps.
In the first initial setup (with initial UImap and CodedUITest1) I can choose whether to use Test builder or existing action recording for generating code. What ever I do it 'goes' to initial UImap. When I create new UI, test builder is started and I can record some actions and when I save it, it is added to newly created UImap in my case called AdvanceSettings. But I can not generate code from existing recording. Why is that? I would like to create automated test cases based on manual test cases with recordings.
Below is my code. I am using CodedUITest1 class for both UImaps. Should I use new class for
every UImap?
If you have some comments on code please do write some.
As I see it. Multiple UImaps are used if you have complex application so you can more easily change something. every GUI element has one UImap so if something changes on that GUI you only edit that UImap. But if you have one UImap and you use proper naming you can also easily replace or re-record certain method. So I am missing big picture with multiple UImaps.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Input;
using System.Windows.Forms;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UITest.Extension;
using Keyboard = Microsoft.VisualStudio.TestTools.UITesting.Keyboard;
using EAEP.AdvanceSettingsClasses;
namespace EAEP
{
/// <summary>
/// Summary description for CodedUITest1
/// </summary>
[CodedUITest]
public class CodedUITest1
{
public CodedUITest1()
{
}
[TestInitialize]
public void InitializationForTest()
{
this.UIMap.AppLaunch();
}
[TestMethod]
public void MainGUIMethod()
{
// To generate code for this test, select "Generate Code for Coded UI Test" from the shortcut menu and select one of the menu items.
// For more information on generated code, see http://go.microsoft.com/fwlink/?LinkId=179463
this.UIMap.AssertMethod1();
this.UIMap.RestoreDefaults();
this.UIMap.AssertMethod1();
}
[TestMethod]
public void AdvanceSettignsWindowMethod()
{
AdvanceSettings advanceSettings = new AdvanceSettings();
advanceSettings.MoreSettingsReopenedAfterCancel();
this.UIMap.AssertVerificationAfterCancel();
advanceSettings.MoreSettingsReopenedAfterOK();
this.UIMap.AssertVerificationAfterOK();
}
#region Additional test attributes
// You can use the following additional attributes as you write your tests:
////Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
// // To generate code for this test, select "Generate Code for Coded UI Test" from the shortcut menu and select one of the menu items.
// // For more information on generated code, see http://go.microsoft.com/fwlink/?LinkId=179463
//}
////Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
// // To generate code for this test, select "Generate Code for Coded UI Test" from the shortcut menu and select one of the menu items.
// // For more information on generated code, see http://go.microsoft.com/fwlink/?LinkId=179463
//}
#endregion
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
private TestContext testContextInstance;
public UIMap UIMap
{
get
{
if ((this.map == null))
{
this.map = new UIMap();
}
return this.map;
}
}
private UIMap map;
}
}
You cann't use multiple UI Maps with the from existing recording feature. this feature always generates code in a map called UIMap. I've explained a bit about these limitation in a blog post i did about integrating specflow with Coded Ui tests
http://rburnham.wordpress.com/2011/05/30/record-your-coded-ui-test-methods/
If you want to use Multiple UIMaps for better maintainability you have to use this method
Record each action individually by right clicking the UIMap and selecting Coded UI Test Builder.
Manually wire up the test to the actions by creating a blank Coded UI Test, update the UIMap it references and then in the test methods call the required actions to perform the test.
Its a limitation that makes what is good about the MTM integration pointless.
Having multiple UIMaps speeds the test execution. Additionally this makes editions, assertions, properties and settings a lot easier.
To create tests for the second UIMap you just right click on it and press "Edit With Coded UI Test Builder"
Regarding the But I can not generate code from existing recording. Why is that? I have no clue - what do you mean by can not?

Possible C# 4.0 compiler error, can others verify?

Since I don't know exactly what part of it alone that triggers the error, I'm not entirely sure how to better label it.
This question is a by-product of the SO question c# code seems to get optimized in an invalid way such that an object value becomes null, which I attempted to help Gary with yesterday evening. He was the one that found out that there was a problem, I've just reduced the problem to a simpler project, and want verification before I go further with it, hence this question here.
I'll post a note on Microsoft Connect if others can verify that they too get this problem, and of course I hope that either Jon, Mads or Eric will take a look at it as well :)
It involves:
3 projects, 2 of which are class libraries, one of which is a console program (this last one isn't needed to reproduce the problem, but just executing this shows the problem, whereas you need to use reflector and look at the compiled code if you don't add it)
Incomplete references and type inference
Generics
The code is available here: code repository.
I'll post a description below of how to make the projects if you rather want to get your hands dirty.
The problem exhibits itself by producing an invalid cast in a method call, before returning a simple generic list, casting it to something strange before returning it. The original code ended up with a cast to a boolean, yes, a boolean. The compiler added a cast from a List<SomeEntityObject> to a boolean, before returning the result, and the method signature said that it would return a List<SomeEntityObject>. This in turn leads to odd problems at runtime, everything from the result of the method call being considered "optimized away" (the original question), or a crash with either BadImageFormatException or InvalidProgramException or one of the similar exceptions.
During my work to reproduce this, I've seen a cast to void[], and the current version of my code now casts to a TypedReference. In one case, Reflector crashes so most likely the code was beyond hope in that case. Your mileage might vary.
Here's what to do to reproduce it:
Note: There is likely that there are more minimal forms that will reproduce the problem, but moving all the code to just one project made it go away. Removing the generics from the classes also makes the problem go away. The code below reproduces the problem each time for me, so I'm leaving it as is.
I apologize for the escaped html characters in the code below, this is Markdown playing a trick on me, if anyone knows how I can rectify it, please let me know, or just edit the question
Create a new Visual Studio 2010 solution containing a console application, for .NET 4.0
Add two new projects, both class libraries, also .NET 4.0 (I'm going to assume they're named ClassLibrary1 and ClassLibrary2)
Adjust all the projects to use the full .NET 4.0 runtime, not just the client profile
Add a reference in the console project to ClassLibrary2
Add a reference in ClassLibrary2 to ClassLibrary 1
Remove the two Class1.cs files that was added by default to the class libraries
In ClassLibrary1, add a reference to System.Runtime.Caching
Add a new file to ClassLibrary1, call it DummyCache.cs, and paste in the following code:
using System;
using System.Collections.Generic;
using System.Runtime.Caching;
namespace ClassLibrary1
{
public class DummyCache<TModel> where TModel : new()
{
public void TriggerMethod<T>()
{
}
// Try commenting this out, note that it is never called!
public void TriggerMethod<T>(T value, CacheItemPolicy policy)
{
}
public CacheItemPolicy GetDefaultCacheItemPolicy()
{
return null;
}
public CacheItemPolicy GetDefaultCacheItemPolicy(IEnumerable<string> dependentKeys, bool createInsertDependency = false)
{
return null;
}
}
}
Add a new file to ClassLibrary2, call it Dummy.cs and paste in the following code:
using System;
using System.Collections.Generic;
using ClassLibrary1;
namespace ClassLibrary2
{
public class Dummy
{
private DummyCache<Dummy> Cache { get; set; }
public void TryCommentingMeOut()
{
Cache.TriggerMethod<Dummy>();
}
public List<Dummy> GetDummies()
{
var policy = Cache.GetDefaultCacheItemPolicy();
return new List<Dummy>();
}
}
}
Paste in the following code in Program.cs in the console project:
using System;
using System.Collections.Generic;
using ClassLibrary2;
namespace ConsoleApplication23
{
class Program
{
static void Main(string[] args)
{
Dummy dummy = new Dummy();
// This will crash with InvalidProgramException
// or BadImageFormatException, or a similar exception
List<Dummy> dummies = dummy.GetDummies();
}
}
}
Build, and ensure there are no compiler errors
Now try running the program. This should crash with one of the more horrible exceptions. I've seen both InvalidProgramException and BadImageFormatException, depending on what the cast ended up as
Look at the generated code of Dummy.GetDummies in Reflector. The source code looks like this:
public List<Dummy> GetDummies()
{
var policy = Cache.GetDefaultCacheItemPolicy();
return new List<Dummy>();
}
however reflector says (for me, it might differ in which cast it chose for you, and in one case Reflector even crashed):
public List<Dummy> GetDummies()
{
List<Dummy> policy = (List<Dummy>)this.Cache.GetDefaultCacheItemPolicy();
TypedReference CS$1$0000 = (TypedReference) new List<Dummy>();
return (List<Dummy>) CS$1$0000;
}
Now, here's a couple of odd things, the above crash/invalid code aside:
Library2, which has Dummy.GetDummies, performs a call to get the default cache policy on the class from Library1. It uses type inference var policy = ..., and the result is an CacheItemPolicy object (null in the code, but type is important).
However, ClassLibrary2 does not have a reference to System.Runtime.Caching, so it should not compile.
And indeed, if you comment out the method in Dummy that is named TryCommentingMeOut, you get:
The type 'System.Runtime.Caching.CacheItemPolicy' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Why having this method present makes the compiler happy I don't know, and I don't even know if this is linked to the current problem or not. Perhaps it is a second bug.
There is a similar method in DummyCache, if you restore the method in Dummy, so that the code again compiles, and then comment out the method in DummyCache that has the "Try commenting this out" comment above it, you get the same compiler error
OK, I downloaded your code and can confirm the problem as described.
I have not done any extensive tinkering with this, but when I run & reflector a Release build all seems OK (= null ref exception and clean disassembly).
Reflector (6.10.11) crashed on the Debug builds.
One more experiment: I wondered about the use of CacheItemPolicies so I replaced it with my own MyCacheItemPolicy (in a 3rd classlib) and the same BadImageFormat exception pops up.
The exception mentions : {"Bad binary signature. (Exception from HRESULT: 0x80131192)"}

Resources