How to uppercase entire variable in Resharper Template? - visual-studio-2012

I have a situation where I want the variable to be capitalized for documentation eg
(trivalized for example)
///AT+$COMMAND$
void At$COMMAND$()
{
}
So I want the user of the template to type in something like "Blah" and that gets used in the method name, but the documentation part gets changed to "BLAH".
eg
///AT+BLAH
void AtBlah()
{
}
Can I do this? I see in the macros I can capitalize the first letter, but I'd like the whole word capitalized. Is it possible to create custom macros?

They just updated documentation to meet changes in macros in Resharper 8. You can check it at http://confluence.jetbrains.com/display/NETCOM/4.04+Live+Template+Macros+%28R8%29
With the new docs it is quite easy, my implementation goes here:
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using JetBrains.DocumentModel;
using JetBrains.ReSharper.Feature.Services.LiveTemplates.Macros;
using JetBrains.ReSharper.Feature.Services.LiveTemplates.Hotspots;
namespace ReSharperPlugin
{
[MacroDefinition("LiveTemplatesMacro.CapitalizeVariable", // macro name should be unique among all other macros, it's recommended to prefix it with your plugin name to achieve that
ShortDescription = "Capitalizes variable {0:list}", // description of the macro to be shown in the list of macros
LongDescription = "Capitalize full name of variable" // long description of the macro to be shown in the area below the list
)]
public class CapitalizeVariableMacro : IMacroDefinition
{
public string GetPlaceholder(IDocument document, IEnumerable<IMacroParameterValue> parameters)
{
return "A";
}
public ParameterInfo[] Parameters
{
get { return new[] {new ParameterInfo(ParameterType.VariableReference)}; }
}
}
[MacroImplementation(Definition = typeof(CapitalizeVariableMacro))]
public class CapitalizeVariableMacroImpl : SimpleMacroImplementation
{
private readonly IMacroParameterValueNew _parameter;
public CapitalizeVariableMacroImpl([Optional] MacroParameterValueCollection parameters)
{
_parameter = parameters.OptionalFirstOrDefault();
}
public override string EvaluateQuickResult(IHotspotContext context)
{
return _parameter == null ? null : _parameter.GetValue().ToUpperInvariant();
}
}
}

Related

How do I assign contents of a string to a text field in Unity 4.6?

I am working on a C# class that imports text data from a web site. That works OK. Where I'm losing it is how to display the text in Unity 4.6 once I have all the text in a string variable. Any advice is appreciated.
Unity 4.6 UI system has component named Text. You can watch video tutorial here. Also I suggest you to check out its API.
As always, you have two options on how to add this component to the game object. You can do it from editor (just click on game object you want to have this component in hierarchy and add Text component). Or you can do it from script using gameObject.AddComponent<Text>().
In case you are not familiar with components yet, I suggest you to read this article.
Anyway, in your script you'll need to add using UnityEngine.UI; at the very top of it, because the Text class is in UnityEngine.UI namespace. Ok, so now back to script that will set the value of Text component.
First you need variable that refers to Text component. It can be done via exposing it to editor:
public class MyClass : MonoBehaviour {
public Text myText;
public void SetText(string text) {
myText.text = text;
}
}
And attaching gameObject with text component to this value in Editor.
Another option:
public class MyClass : MonoBehaviour {
public void SetText(string text) {
// you can try to get this component
var myText = gameObject.GetComponent<Text>();
// but it can be null, so you might want to add it
if (myText == null) {
myText = gameObject.AddComponent<Text>();
}
myText.text = text;
}
}
Previous script is not a good example, because GetComponent is actually expensive. So you might want to cache it’s reference:
public class MyClass : MonoBehaviour {
Text myText;
public void SetText(string text) {
if (myText == null) {
// looks like we need to get it or add
myText = gameObject.GetComponent<Text>();
// and again it can be null
if (myText == null) {
myText = gameObject.AddComponent<Text>();
}
}
// now we can set the value
myText.text = text;
}
}
BTW, the patter of ‘GetComponent or Add if it doesn’t exist yet’ is so common, that usually in Unity you want to define function
static public class MethodExtensionForMonoBehaviourTransform {
static public T GetOrAddComponent<T> (this Component child) where T: Component {
T result = child.GetComponent<T>();
if (result == null) {
result = child.gameObject.AddComponent<T>();
}
return result;
}
}
So you can use it as:
public class MyClass : MonoBehaviour {
Text myText;
public void SetText(string text) {
if (myText == null) {
// looks like we need to get it or add
myText = gameObject.GetOrAddComponent<Text>();
}
// now we can set the value
myText.text = text;
}
}
make sure you import the ui library - using UnityEngine.UI
gameObject.GetComponent<Text>().text - replace .text with any other field for UI Text
I assume that the issue is creating dynamic sized "textbox" rather than just assigning the string to a GUIText GameObject. (If not - just put a GUIText GameObject into your scene, access it via a GUIText variable in your script and use myGUIText.text = myString in Start or Update.)
If I am correct in my assumption, then I think you should just be using a GUI Label:
http://docs.unity3d.com/ScriptReference/GUI.Label.html
If you need to split the string up to place text into different labels or GUITexts, you will need to use substrings

Can I use something like DebuggerTypeProxyAttribute on a type that I don't own?

I've got an IClaimsPrincipal variable, and I'd like to see how many claims are in it. Navigating through the properties in the watch window is complicated, so I'd like to customize how this object is displayed.
I'm aware of the [DebuggerTypeProxy] attribute, which initially looked like it might do what I want. Unfortunately, it needs to be attached to the class, and I don't "own" the class. In this case it's a Microsoft.IdentityModel.Claims.ClaimsPrincipal.
I'd like to display the value of IClaimsPrincipal.Identities[0].Claims.Count.
Is there any way, using [DebuggerTypeProxy] or similar, to customize how the value of a type that I don't own is displayed in the watch window?
Example of DebuggerTypeProxyAttribute applied to KeyValuePair showing only the Value member:
using System.Collections.Generic;
using System.Diagnostics;
[assembly: DebuggerTypeProxy(typeof(ConsoleApp2.KeyValuePairDebuggerTypeProxy<,>), Target = typeof(KeyValuePair<,>))]
// alternative format [assembly: DebuggerTypeProxy(typeof(ConsoleApp2.KeyValuePairDebuggerTypeProxy<,>), TargetTypeName = "System.Collections.Generic.KeyValuePair`2")]
namespace ConsoleApp2
{
class KeyValuePairDebuggerTypeProxy<TKey, TValue>
{
private KeyValuePair<TKey, TValue> _keyValuePair; // beeing non-public this member is hidden
//public TKey Key => _keyValuePair.Key;
public TValue Value => _keyValuePair.Value;
public KeyValuePairDebuggerTypeProxy(KeyValuePair<TKey, TValue> keyValuePair)
{
_keyValuePair = keyValuePair;
}
}
class Program
{
static void Main(string[] args)
{
var dictionary = new Dictionary<int, string>() { [1] = "one", [2] = "two" };
Debugger.Break();
}
}
}
Tested on Visual Studio 2017
The best I've come up with so far is to call a method:
public static class DebuggerDisplays
{
public static int ClaimsPrincipal(IClaimsPrincipal claimsPrincipal)
{
return claimsPrincipal.Identities[0].Claims.Count;
}
}
...from the watch window:
DebuggerDisplays.ClaimsPrincipal(_thePrincipal),ac = 10
The ",ac" suppresses the "This expression causes side effects and will not be evaluated".
However, note that when this goes out of scope, Visual Studio will simply grey out the watch window entry, even with the ",ac". To avoid this, you'll need to ensure that everything is fully qualified, which means that you'll end up with extremely long expressions in the watch window.

Get job title using System.DirectoryServices.AccountManagement

I've successfully used the AccountManagement code to retrieve basic AD information but it's only returning a very limited set of information about the returned object. How can I get extended information from AD using the AccountManagement functionality. Specifically the Job Title or title as it seems to be called in my instance of AD.
I know how to do it using the older DirectoryServices but I'd like to know how to do it using the new namespace.
Yes, the default set of properties on UserPrincipal is quite limited - but the great part is: there's a neat extensibility story in place!
You need to define a class descending from UserPrincipal and then you can very easily get access to a lot more properties, if needed.
The skeleton would look something like this:
namespace ADExtended
{
[DirectoryRdnPrefix("CN")]
[DirectoryObjectClass("User")]
public class UserPrincipalEx : UserPrincipal
{
// Inplement the constructor using the base class constructor.
public UserPrincipalEx(PrincipalContext context) : base(context)
{ }
// Implement the constructor with initialization parameters.
public UserPrincipalEx(PrincipalContext context,
string samAccountName,
string password,
bool enabled) : base(context, samAccountName, password, enabled)
{}
UserPrincipalExSearchFilter searchFilter;
new public UserPrincipalExSearchFilter AdvancedSearchFilter
{
get
{
if (null == searchFilter)
searchFilter = new UserPrincipalExSearchFilter(this);
return searchFilter;
}
}
// Create the "Title" property.
[DirectoryProperty("title")]
public string Title
{
get
{
if (ExtensionGet("title").Length != 1)
return string.Empty;
return (string)ExtensionGet("title")[0];
}
set { ExtensionSet("title", value); }
}
// Implement the overloaded search method FindByIdentity.
public static new UserPrincipalEx FindByIdentity(PrincipalContext context, string identityValue)
{
return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityValue);
}
// Implement the overloaded search method FindByIdentity.
public static new UserPrincipalEx FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue)
{
return (UserPrincipalEx)FindByIdentityWithType(context, typeof(UserPrincipalEx), identityType, identityValue);
}
}
}
And that's really almost all there is! The ExtensionGet and ExtensionSet methods allow you to "reach down" into the underlying directory entry and grab out all the attributes you might be interested in....
Now, in your code, use your new UserPrincipalEx class instead of UserPrincipal:
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// Search the directory for the new object.
UserPrincipalEx myUser = UserPrincipalEx.FindByIdentity(ctx, "someUserName");
if(myUser != null)
{
// get the title which is now available on your "myUser" object!
string title = myUser.Title;
}
}
Read all about the System.DirectoryServices.AccountManagement namespace and its extensibility story here:
Managing Directory Security Principals in the .NET Framework 3.5
Update: sorry - here's the UserPrincipalExSearchFilter class - missed that one in the original post. It just shows the ability to also extend the search filters, if need be:
public class UserPrincipalExSearchFilter : AdvancedFilters
{
public UserPrincipalExSearchFilter(Principal p) : base(p) { }
public void LogonCount(int value, MatchType mt)
{
this.AdvancedFilterSet("LogonCount", value, typeof(int), mt);
}
}
To Augment the above I have knocked up an extension method to call ExtensionGet. It uses reflection to get hold of the protected method you would otherwise have to inherit. You might need to use this if you are returning UserPrincipalObjects from Groups.Members, for example
public static class AccountManagmentExtensions
{
public static string ExtensionGet(this UserPrincipal up, string key)
{
string value = null;
MethodInfo mi = up.GetType()
.GetMethod("ExtensionGet", BindingFlags.NonPublic | BindingFlags.Instance);
Func<UserPrincipal, string, object[]> extensionGet = (k,v) =>
((object[])mi.Invoke(k, new object[] { v }));
if (extensionGet(up,key).Length > 0)
{
value = (string)extensionGet(up, key)[0];
}
return value;
}
}
There are simpler ways of getting to that info. Here is the way I got to Job Title in VB.NET:
Dim yourDomain As New PrincipalContext(ContextType.Domain, "yourcompany.local")
Dim user1 As UserPrincipal = UserPrincipal.FindByIdentity(yourDomain, principal.Identity.Name)
Dim Entry As DirectoryServices.DirectoryEntry = user1.GetUnderlyingObject()
Dim JobTitle As String = Entry.Properties.Item("Title").Value.ToString
To expand on Programmierus' comment, here is a simple way to do this on the fly in C#.
public static string GetProperty(UserPrincipal userPrincipal, string property)
{
DirectoryEntry d = (DirectoryEntry)userPrincipal.GetUnderlyingObject();
return d.Properties[property]?.Value?.ToString();
}

Help With Error C#: An object reference is required for the non-static field, method, or property RpgTutorial.Character.Swordsmanship

I am very new to C# and programming in general and I'm having the error (described in the title box) when I run this code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace RpgTutorial
{
public class HeroSkills : Character
{
public int Skill()
{
if (Hero.Swordsmanship = 10)
{
}
}
}
}
Now I know I need to create a reference to Swordsmanship, but how exactly would I do that? Thank you for any help!
If you're trying to access the Swordsmanship property of the same object that the method would be called for, then you can access it via the this reference:
if (this.Swordsmanship == 10)
{
...
}
Is a Hero a subclass of Character (or the other way around)? If so, you can reference the property Swordsmanship like this:
if (this.Swordsmanship == 10)
{
...
}
Otherwise if you are finding yourself needing to reference a 'hero', you can add a constructor (and property) to your HeroSkills class like this:
public HeroSkills : Character
{
public Hero CurrentHero
{
get;
set;
}
public HeroSkills(Hero hero)
{
this.CurrentHero = hero;
}
...
Note that the this keyword is not required, but signifies that the property you are accessing is a member of your class. This can help you in readability later on. You can then reference the CurrentHero around your class in your various methods like the Skill() as so:
if (this.CurrentHero.Swordsmanship == 10)
{
...
}
You would use your newly modified class elsewhere in code like this:
Hero player1 = //some hero variable
var skills = new HeroSkills(player1);
int currentSkill = skills.Skill();

Subsonic 3, how to CRUD using LinqTemplates?

I am new to Subsonic, and it seems that I cant find out a natural way to do CRUD operations using the LINQ template classes. I guess in ActiveRecord, you could:
Product p = new Product();
p.ProductCode = "xxx";
p.Add();
Using the LINQTemplate generated classes however, how can I do the same thing? I can only use something like this below to insert a product object:
db.Insert.Into<UnleashedSaaS.PRODUCT>(prod => prod.Code, prod => prod.Description).Values("Product1", "Product1 Desc").Execute();
Who could kindly give me some hints? I'd really appreciate it.
All the CRUD happens in SubSonicRepository, which you can derive from. For example, I would have a class like this:
public class ProductRepository : SubSonicRepository<Product> {
public ProductRepository() : base(new NorthwindDB()) { }
// need this here because base doesn't expose the DB class that I know of
protected NorthwindDB _db;
protected NorthwindDB DB {
get {
if (_db == null) _db = new NorthwindDB();
return _db;
}
}
public void Save(Product product) {
if (product.ProductId == 0) {
Add(product); // Add is part of SubSonicRepository
} else {
Update(product);
}
}
public void Delete(Product product) { ... }
public List<Product> ListAll() {
var products = from p in DB.Products
select p;
return products.ToList();
}
public Product GetById(int id) {
return DB.GetByKey(id);
}
}
And so on. It's nice because you can consolidate all your data access methods in one place. If you have Sprocs, they're generated as methods on DB as well.
When I get time I'm going to work on adding a Save method to SubSonicRepository directly so you don't have to do the check yourself to see which method (Add or Update) to call.
I have modified the Classes.tt file to include:
public partial class <#=tbl.ClassName#>Repository : SubSonicRepository<<#=tbl.ClassName#>>
{
public <#=tbl.ClassName#>Repository() : base(new <#=DatabaseName#>DB()) { }
}
Insert that bunch of lines between
<# foreach(Table tbl in tables){#>
and
/// <summary>
right at the top, near the namespace declaration, in my file it can be inserted in line 18.
The last thing to do is to add another "using" statement, in line 10, the next line after System.Linq statement. Now it should look like:
using System.Linq;
using SubSonic.Repository;
That will generate a repository to give you access to basic functionality, but can be modified in another partial class.
Hope that helps.

Resources