Passing a String by Reference in Metro/C++? - string

I'm working on a C++ Metro style app and have to pass a string by reference (somehow). At first, I passed the String^ which doesn't work because strings are immutable how I have found out.
What would be a proper way to pass a string by reference?
Edit: OK, it seems that it's not that easy since the answers and comments suggest to use return values. But as far as I think this is not applicable in my situation: In this Metro app I have two pages and a string should be "shared" across those two pages.
So in the main page I do this in a click event:
this->Frame->Navigate(newPage, this->TestString);
In the OnNavigatedTo event of the second page I convert the second parameter to a String^ and change it. Then I use this->Frame->GoBack() to navigate back to the first page. There I'd like to have access to the changed string. Unfortunately, GoBack() doesn't allow to pass any parameters as far as I know.

You can use a tracking reference:
void ModifyTheParameter(String^% value) {
value = gcnew String("Blah");
}
That would modify the original variable you passed in as parameter (see MSDN for more info and examples). It would then be used just as any other method taking a String^ parameter.
But if possible, avoid using tracking references as parameters. I'd recommend just returning a String^ and assigning that to the original variable.
Yet another possibility: You could just create some kind of View-agnostic DataModel that contains your String (and possibly other data that you work with). You could then pass that DataModel to your method. Since the DataModel variable isn't changed (just a property of it), you wouldn't need to pass a reference to it.

See below an example of a function f which takes as a parameter a reference to a std::string.
std::string someString;
void f(std::string& s);
f(someString);

Related

Using Roslyn, if I have an IdentifierNameSyntax, can I find the member type it refers to (field, property, method...)

I am attempting to use the Roslyn SDK and StackExchange.Precompilation (thank you!) to implement aspect-oriented programming in C#6. My specific problem right now is, starting with an IdentifierNameSyntax instance, I want to find the "member type" (method, property, field, var, etc.) that the identifier refers to. (How) can this be done?
Background:
The first proof-of-concept I am working on is some good old design-by-contract. I have a NonNullAttribute which can be applied to parameters, properties, or method return values. Along with the attribute there is a class implementing the StackExchange.Precompilation.ICompileModule interface, which on compilation will insert null checks on the marked parameters or return values.
This is the same idea as PostSharp's NonNullAttribute, but the transformation is being done on one of Roslyn's syntax trees, not on an already compiled assembly. It is also similar to Code Contracts, but with a declarative attribute approach, and again operating on syntax trees not IL.
For example, this source code:
[return: NonNull]
public string Capitalize([NonNull] string text) {
return text.ToUpper();
}
will be transformed into this during precompilation:
[return: NonNull]
public string Capitalize([NonNull] string text) {
if (Object.Equals(text, null))
throw new ArgumentNullException(nameof(text));
var result = text.ToUpper();
if (Object.Equals(result, null))
throw new PostconditionFailedException("Result cannot be null.");
return result;
}
(PostconditionFailedException is a custom exception I made to compliment ArgumentException for return values. If there is already something like this in the framework please let me know.)
For properties with this attribute, there would be a similar transformation, but with preconditions and postconditions implemented separately in the set and get accessors, respectively.
The specific reason I need to find the "member type" of an identifier here is for an optimization on implementing postconditions. Note in the post-compilation sample above, the value that would have been returned is stored in a local variable, checked, and then the local is returned. This storage is necessary for transforming return statements that evaluate a method or complex expression, but if the returned expression is just a field or local variable reference, creating that temporary storage local is wasteful.
So, when the return statement is being scanned, I first check if the statement is of the form ReturnKeyword-IdentifierSyntaxToken-SemicolonToken. If so, I then need to check what that identifier refers to, so I avoid that local variable allocation if the referent is a field or var.
Update
For more context, check out the project this is in reference to on GitHub.
You'll need to use SemanticModel.GetSymbolInfo to determine the symbol an identifier binds to.
Use SemanticModel.GetTypeInfo.Type to obtain the TypeInfo and use it to explore the Type

How do I add int field into ListView?

So I'm trying to fill a table, which is made by using ListView. "a" is some int, and obviously I can not just add an item like this, cuz it asks for string^. How do I convert my int to this string^? And what's the difference between usual string and string^?
System::Windows::Forms::ListViewItem^ listView1Item;
private: System::Windows::Forms::ListView^ listView1;
...
listView1Item = gcnew Windows::Forms::ListViewItem(a);
listView1->Items->Add(listView1Item);
To convert int a to a string, call a.ToString(). ToString is defined on the .Net base class Object, so just about everything has a ToString you can call. (Since you're in C++/CLI, things that are purely unmanaged will not have a ToString method. But anything that's managed, or primitives that are also used in .Net (e.g., int), will.)
As for the difference between String and String^, I'm not sure exactly what you mean by the "usual string". I'm not sure whether you're referring to C++'s std::string, or to .Net's System::String, just without the ^. String^ refers to the .Net System::String class, as a manged reference. Managed references are roughly equivalent to unmanaged pointers, but the garbage collector is allowed to move things around as it does its work, and the managed reference continues to point at the proper object.
The answer was:
System::Convert::ToString()
Thx everybody for help =)

How to auto-generate early bound properties for Entity specific (ie Local) Option Set text values?

After spending a year working with the Microsoft.Xrm.Sdk namespace, I just discovered yesterday the Entity.FormattedValues property contains the text value for Entity specific (ie Local) Option Set texts.
The reason I didn't discover it before, is there is no early bound method of getting the value. i.e. entity.new_myOptionSet is of type OptionSetValue which only contains the int value. You have to call entity.FormattedValues["new_myoptionset"] to get the string text value of the OptionSetValue.
Therefore, I'd like to get the crmsrvcutil to auto-generate a text property for local option sets. i.e. Along with Entity.new_myOptionSet being generated as it currently does, Entity.new_myOptionSetText would be generated as well.
I've looked into the Microsoft.Crm.Services.Utility.ICodeGenerationService, but that looks like it is mostly for specifying what CodeGenerationType something should be...
Is there a way supported way using CrmServiceUtil to add these properties, or am I better off writing a custom app that I can run that can generate these properties as a partial class to the auto-generated ones?
Edit - Example of the code that I would like to be generated
Currently, whenever I need to access the text value of a OptionSetValue, I use this code:
var textValue = OptionSetCache.GetText(service, entity, e => e.New_MyOptionSet);
The option set cache will use the entity.LogicalName, and the property expression to determine the name of the option set that I'm asking for. It will then query the SDK using the RetrieveAttriubteRequest, to get a list of the option set int and text values, which it then caches so it doesn't have to hit CRM again. It then looks up the int value of the New_MyOptionSet of the entity and cross references it with the cached list, to get the text value of the OptionSet.
Instead of doing all of that, I can just do this (assuming that the entity has been retrieved from the server, and not just populated client side):
var textValue = entity.FormattedValues["new_myoptionset"];
but the "new_myoptionset" is no longer early bound. I would like the early bound entity classes that gets generated to also generate an extra "Text" property for OptionSetValue properties that calls the above line, so my entity would have this added to it:
public string New_MyOptionSetText {
return this.GetFormattedAttributeValue("new_myoptionset"); // this is a protected method on the Entity class itself...
}
Could you utilize the CrmServiceUtil extension that will generate enums for your OptionSets and then add your new_myOptionSetText property to a partial class that compares the int value to the enums and returns the enum string
Again, I think specifically for this case, getting CrmSvcUtil.exe to generate the code you want is a great idea, but more generally, you can access the property name via reflection using an approach similar to the accepted answer # workarounds for nameof() operator in C#: typesafe databinding.
var textValue = entity.FormattedValues["new_myoptionset"];
// becomes
var textValue = entity.FormattedValues
[
// renamed the class from Nameof to NameOf
NameOf(Xrm.MyEntity).Property(x => x.new_MyOptionSet).ToLower()
];
The latest version of the CRM Early Bound Generator includes a Fields struct that that contains the field names. This allows accessing the FormattedValues to be as simple as this:
var textValue = entity.FormattedValues[MyEntity.Fields.new_MyOptionSet];
You could create a new property via an interface for the CrmSvcUtil, but that's a lot of work for a fairly simple call, and I don't think it justifies creating additional properties.

Pass a dynamic variable in a static parameter of a method in C# 4

This is what I am trying to do:
public void method(int myVal, string myOtherVal)
{
// doing something
}
dynamic myVar = new SomeDynamicObjectImplementer();
method(myVar.IntProperty, myVar.StringProperty);
Note that my properties are also DynamicObjects. My problem is that the TryConvert method is never called and that I get a runtime error saying the method signature is invalid.
The following is working great:
string strVar = myVar.StringProperty;
int intVar = myVar.IntProperty;
And I would like to avoid
method((int)myVar.IntProperty, (string)myVar.StringProperty);
Is it possible to override something in DynamicObject to allow this? (or something else)
Thank you
The problem is your assumption that it will try a dynamic implicit convert on arguments of an dynamic invocation to make a method call work, this is not true.
When your arguments aren't statically typed, it will use the runtime type to find the best matching method (if the runtime type matches the static rules for implicit conversion to the argument type this will work too), since your your IntProperty,StringProperty seem to be returning a DynamicObject rather than an Int and a String or something that could statically be converter implicitly, this lookup will fail.
If SomeDynamicObjectImplementer could actually return an Int for IntProperty and a String for StringProperty your method call for without casting would actually work. It's also probably a better dynamic typing practice if you data type is based on the actually type of data rather than usage using try convert. You could add actually implicit convert methods for every possible type that you could return to that returned DynamicObject type, but that could cause strange resolution issues to depending on how much you are overloading.
However, another option to keep your dynamic implementation the same is to mix a little controlled static typing in, you can use ImpromputInterface (in nuget) to put an interface on top of a dynamic object, if you do that then the TryConvert method would be called on your returned DynamicObjects.
public interface ISomeStaticInterface{
int IntProperty {get;}
string StringProperty {get;}
}
...
var myVar = new SomeDynamicObjectImplementer().ActLike<ISomeStaticInterface>();
method(myVar.IntProperty, myVar.StringProperty);
Instead of using myVar.IntProperty can't you just put them in variables first, like you already did, and then use then for your method?
so method(intVar , strVar); seems fine. At least more elegant than casting.
Of course, if you're already certain your object will have IntProperty and StringProperty, why not just make an actual object with those properties instead?
Why are you doing the cast?
method(myVar.IntProperty, myVar.StringProperty);
should compile.
If the two properties must be the types suggested by the names then they shouldn't be dynamic.

ios detachNewThreadSelector, how to withObjects?

I know that
detachNewThreadSelector:toTarget:withObject
can have a (id)anArgument. I have searched it that it can work for NSString.
However, when I pass an integer or size_t, it crashed. Can somebody tell me what is (id)anArgument?
What's more, how can I pass more than one parameter to the thread? For example, I have a function,
-(NSInteger)getIneger: (NSInteger) pageNumber withName(NSString*) filename ;
something like that.
Thanks
What (id)anArgument tells you is that you need to pass an Objective-C argument. Since neither integer nor size_t are Objective-C objects, the application crashes. You will need to package them within an NSNumber for this to work. You will also have to alter the method to take in an NSNumber rather than the int. To pass two or more arguments, I suggest you use an NSDictionary object to pass values based on keys. You can define a method that takes in an NSDictionary object, unpacks the values and calls the original method you had intended to call.

Resources