How to activate C# 10 features Visual Studio 2022 - .net-6.0

I try to use the newest C# 10 features in Visual Studio 2022 Preview 3. The compiler does not recognize the new keywords required or field. global using seems to work.
public required string Name { get; init; }
public DateTime HiredDate{ get; init => field = value.Date(); }
Null parameter checking doesn't compile:
public void NullParameterCheck(string arg!!) { ... }
I also tried to set the language version to preview in the .csproj:
<LangVersion>preview</LangVersion>
Is there any setting I missed?

Finally I found part of the solution. I have to add
<LangVersion>preview</LangVersion>
<EnablePreviewFeatures>true</EnablePreviewFeatures>
to the .csproj file. Null parameter checks work, but not required and field.

this is what I use in .csproj file:
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>preview</LangVersion>
<EnablePreviewFeatures>true</EnablePreviewFeatures>
<GenerateRequiresPreviewFeaturesAttribute>true</GenerateRequiresPreviewFeaturesAttribute>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

Related

Visual Studio snippet - How to convert first letter to lowercase

In Visual Studio, I would like to update the fullprop snipped to automatically convert the field name according to property name: (and so only enter "property name" & "type")
public string MyTest
{
get => _myTest;
set
{
if (_myTest == value) return;
_myTest = value;
RaisePropertyChanged();
}
}
private string _myTest;
I can't find a way to convert MyProperty in myProperty.
I found this topic which seems to work with VSCode but it doesn't work in Visual Studio. Snippet in VSCode seems to be different from Visual Studio as $1$ works in visual studio but ${1} doesn't work. So is there an equivalent way in Visual Studio ?
Thanks for your help !

Xamarin ... migration to .NET Standard 2.0 failed

I'm trying to migrate my PCL project to the new "net standard" but for now I failed.
Currently I got the following exception :
System.MissingMethodException: 'Method not found: 'Void Xamarin.Forms.Xaml.Internals.SimpleValueTargetProvider..ctor(System.Object[], System.Object, Xamarin.Forms.Internals.INameScope)'.'
It happend directly from the 'InitializeComponent' of a page where I have the following xaml tag:
<Image Source="{ns_uc:ImageResource i_home_on.png}"/>
where the 'ImageResource' is an extension marker, this one works like a charm in my PCL project. Here is a part of the definition :
public class ImageResourceExtension : IMarkupExtension
But this class is not called from my new .NET Standard project !
In the .csproj I have the following references, it should be enough ?
<PackageReference Include="System.ComponentModel" Version="4.3.0" />
<PackageReference Include="Xamarin.Forms" Version="3.4.0.1008975" />
So, if someone have an idea because I have already spend 2 days in this migration, without success :-(
BTW, it seems I'm not alone : https://forums.xamarin.com/discussion/101999/cant-use-imarkupextension-in-a-net-standard-library
Thanks for your help
1.System.ComponentModel is a NuGet package in some NetStandard versions.Try to install it if it doesn't exist.
2.You can use <Image Source="myImage.png"/> directly instead of using IMarkupExtension in .net standard project.
3.The implement of ImageResourceExtension maybe different in PCL project and .net standard 2.0 project. Here is an implement in official demo you can refer:
[ContentProperty("Source")]
class ImageResourceExtension : IMarkupExtension<ImageSource>
{
public string Source { set; get; }
public ImageSource ProvideValue(IServiceProvider serviceProvider)
{
if (String.IsNullOrEmpty(Source))
{
IXmlLineInfoProvider lineInfoProvider = serviceProvider.GetService(typeof(IXmlLineInfoProvider)) as IXmlLineInfoProvider;
IXmlLineInfo lineInfo = (lineInfoProvider != null) ? lineInfoProvider.XmlLineInfo : new XmlLineInfo();
throw new XamlParseException("ImageResourceExtension requires Source property to be set", lineInfo);
}
string assemblyName = GetType().GetTypeInfo().Assembly.GetName().Name;
return ImageSource.FromResource(assemblyName + "." + Source, typeof(ImageResourceExtension).GetTypeInfo().Assembly);
}
object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
{
return (this as IMarkupExtension<ImageSource>).ProvideValue(serviceProvider);
}
}
You can refer the demo below to fix your project.
Refer:Demo of ImageResourceExtension
Documents of Markup Extensions
I would follow James Montemagno's steps:
https://montemagno.com/how-to-convert-a-pcl-library-to-net-standard-and-keep-git-history/
I followed this video from the Xamarin show:
https://channel9.msdn.com/Shows/XamarinShow/Snack-Pack-15-Upgrading-to-XamarinForms-to-NET-Standard
I tried it on my own the first go around and failed miserably. The second go around I followed the instructions from the video exactly and everything worked.

Get a Xamarin assembly build date on iOS, Android and OS X

In my code I need a Xamarin assembly build date. On Windows I can use linker time stamp. However on iOS this does not work. I guess it would not work on OS X too as Portable Executable header is specific to Windows.
There is also an option to embed a resource with a date, however I would like to avoid using resources in this particular project.
Are there any way to find a Xamarin assembly build date that works on iOS, Android and OS X?
One approach would be to use an MSBuild task to substitute the build time into a string that is returned by a property on the app. We are using this approach successfully in an app that has Xamarin.Forms, Xamarin.Android, and Xamarin.iOS projects.
If using msbuild, this can be an MSBuild inline task, while on Mac using xbuild, it will need to be an MSBuild custom task compiled for Mono.
EDIT:
Simplified by moving all of the logic into the build task, and using Regex instead of simple string replace so that the file can be modified by each build without a "reset".
The MSBuild inline task definition (saved in a SetBuildDate.targets file local to the Xamarin.Forms project for this example):
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion="12.0">
<UsingTask TaskName="SetBuildDate" TaskFactory="CodeTaskFactory"
AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v12.0.dll">
<ParameterGroup>
<FilePath ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Code Type="Fragment" Language="cs"><![CDATA[
DateTime now = DateTime.UtcNow;
string buildDate = now.ToString("F");
string replacement = string.Format("BuildDate => \"{0}\"", buildDate);
string pattern = #"BuildDate => ""([^""]*)""";
string content = File.ReadAllText(FilePath);
System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(pattern);
content = rgx.Replace(content, replacement);
File.WriteAllText(FilePath, content);
File.SetLastWriteTimeUtc(FilePath, now);
]]></Code>
</Task>
</UsingTask>
</Project>
EDIT:
Added an MSBuild Exec step to remove readonly attribute. Gotta love TFS.
Invoking the MSBuild task (inline or compiled, inline approach is commented for xbuild) in the Xamarin.Forms csproj file in target BeforeBuild:
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets. -->
<!--<Import Project="SetBuildDate.targets" />-->
<UsingTask AssemblyFile="$(MSBuildProjectDirectory)\BI.Framework.BuildExtensions.dll" TaskName="Some.Framework.BuildExtensions.BuildDateTask" />
<Target Name="BeforeBuild">
<Exec Command="attrib $(MSBuildProjectDirectory)\BuildMetadata.cs -r" />
<!--<SetBuildDate FilePath="$(MSBuildProjectDirectory)\BuildMetadata.cs" />-->
<BuildDateTask FilePath="$(MSBuildProjectDirectory)\BuildMetadata.cs" />
</Target>
The FilePath property is set to a BuildMetadata.cs file in the Xamarin.Forms project that contains a simple class with a string property BuildDate, into which the build time will be substituted:
public class BuildMetadata
{
public static string BuildDate => "This can be any arbitrary string";
}
Add this file BuildMetadata.cs to project. It will be modified by every build, but in a manner that allows repeated builds (repeated replacements), so you may include or omit it in source control as desired.
ADDED:
Here is a custom MSBuild task to replace the MSBuild inline task for when building with xbuild on Mac:
using System;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Some.Framework.BuildExtensions
{
public class BuildDateTask : Task
{
#region Methods
/// <summary>
/// Called automatically when the task is run.
/// </summary>
/// <returns><c>true</c>for task success, <c>false</c> otherwise.</returns>
public override bool Execute()
{
const string pattern = #"BuildDate => ""([^""]*)""";
var now = DateTime.UtcNow;
var buildDate = now.ToString("F");
var replacement = $"BuildDate => \"{buildDate}\"";
var content = File.ReadAllText(FilePath);
var rgx = new Regex(pattern);
content = rgx.Replace(content, replacement);
File.WriteAllText(FilePath, content);
File.SetLastWriteTimeUtc(FilePath, now);
return true;
}
#endregion Methods
#region Properties
[Required]
public string FilePath { get; set; }
#endregion Properties
}
}
Build this custom task for Release via xbuild, then copy the output custom task dll to the project directory of the project for which you want to set the build date.

How to encapsulate User Setting (Options Page) in Visual Studio 2010 AddIn

I'm currently developping a Visual Studio Extension and I have a question about Options Page. Options Page allows user to save setting about your Extension. Visual Studio handle a lot of work for us.
I created the Options Page.
public class VisualStudioParameter : DialogPage
{
private string _tfsServerUrl = DefaultParameter.TfsServerUrl;
[Category("TFS Parameters")]
[DisplayName(#"Server Name")]
[Description("The URL of your TFS Server")]
public string TfsServerUrl
{
get { return _tfsServerUrl; }
set { _tfsServerUrl = value; }
}
}
First, I created a method in the Visual Studio Package to acces to the Options Page.
Okay so now, from my Package, I can easily acces to the settings.
partial class SpecFlowTfsLinkerExtensionPackage : Package : IParameter
{
....
....
public string GetTfsServerUrl()
{
return ((VisualStudioParameter) GetDialogPage(typeof (VisualStudioParameter))).TfsServerUrl;
}
}
Now, I want to be able, in another library (Another project, included in the VSIX Package), to get easily these values. I don't want to reference the Visual Studio AddIn Package in my library.
I also have Unit Test so I'm going to create an Interface. During Unit Test, I going to Mock the object.
public interface IParameter
{
string GetTfsServerUrl();
}
Do you have any idea about how I can develop a clean solution to get these parameters from another assembly ?
Do you think the better solution is to inject the AddIn dependency in my library ?
If you already developed a Visual Studio Extension, How did you encapsulated the user setting from your core assembly ?
Thanks a lot.
You can try something like that:
// Access DTE infrastructure
EnvDTE.DTE dte = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
// Access options page
var props = dte.get_Properties(#"Your Extension", "General");
var pathProperty = props.Item("TfsServerUrl");
path = pathProperty.Value as string;

Is the redistributable ReportViewer 2010 RC available in other languages?

I need to deploy the language packs for the ReportViewer 2010 control (the english one is installed and working perfectly). Before, with ReportViewer 2008 and 2005, all the supported laguages were available on the MS downloads site. I can't seem to find them for the RC of 2010 -- are they available anywhere?
From MSDN:
To use the localized version of the
ReportViewer control redistributable
that comes with Visual Studio, do the
following:
1.Run ReportViewer.exe.
2.Navigate to the folder that contains the language pack you want to use.
Language pack folders are located at
%PROGRAMFILES%\Microsoft
SDKs\Windows\v7.0A\BootStrapper\Packages\ReportViewer\.
3.Run ReportViewerLP.exe.
Is there a generic language pack for VS 2010 RC that would have the localized report viewers as well?
It is not more easy to implement the IReportViewerMessages3 interface?
From MSDN
public interface IReportViewerMessages3 :
IReportViewerMessages2, IReportViewerMessages
This implementation is loaded by the ReportViewer control via a custom application setting in the Web.config configuration file with the key ReportViewerMessages
<appSettings>
<add key="ReportViewerMessages" value="MyNamespace.MyClass, APP_CODE" />
</appSettings>
Or if you are on winForms or WPF:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CCustomMessageClass myMessageClass = new CCustomMessageClass();
reportViewer1.Messages = myMessageClass;
this.reportViewer1.RefreshReport();
}
}
public class CCustomMessageClass : IReportViewerMessages
{
#region IReportViewerMessages Members
public string BackButtonToolTip
{
get { return ("BackButtonToolTip here."); }
}
...
#endregion
}

Resources