Passing Guid to Command Line parser Library in C# - c#

I am using the nuget package Command Line Parser for parsing command line arguments in C#.
How do I pass a GUID from command line?
ApplicationName.exe -g="3a0e5412-0971-4e0e-aebc-29dd09907b31"
does not work.
My CommandLineArgs class is
[Option('g', "sampleguid", Required = true, HelpText = "Enter a sample GUID")]
public Guid MyGuid { get; set; }

First, there is no built-in functionality for Guid. Second, make sure you're using the latest version 2.6.0.5. You can install it through nuget -> search for "CommandLineArgumentsParser".
Once you've installed the latest version, you can interpret custom structures as such:
var parser = new CommandLineParser.CommandLineParser();
var guidArgument = new ValueArgument<Guid>('g', "guid", "Guid of something");
guidArgument.ConvertValueHandler = Guid.Parse;
parser.Arguments.Add(guidArgument);
parser.ParseCommandLine(args);
// the actual guid from command line.
var parsedGuid = guidArgument.Value;
If you want to keep your current version, you need to treat Guid as string when parsing, and later do custom validation by yourself.
http://commandlineparser.codeplex.com/wikipage?title=More%20thorough%20examples&referringTitle=Home

As you can see from GUID is not working for input parameter, the Guid parsing issue was already fixed. (However, if you use Guid?, it still does not work.)

Have you tried dropping the "=" and using a " " (space) instead?
Like: ApplicationName.exe -g "3a0e5412-0971-4e0e-aebc-29dd09907b31"

Related

Azure.Messaging.EventGrid vs Azure.EventGrid IotHubDeviceTelemetryEventData missing Constructor?

I am attempting to use the newer Azure.Messaging.EventGrid over the traditional Azure.EventGrid. I am getting hung up on my unit tests attempting to create object of type IotHubDeviceTelemetryEventData(). In the older library, I was able to create this no problem using the following convention.
return new object[]
{
new
{
id = "73813f6e-4d43-eb85-d6f1-f2b6a0657731",
topic = "testTopic",
data = new IotHubDeviceTelemetryEventData <-- New Up the object (no problem!)
{
Body = body} <-- Body has a setter. Great!
,
eventType = "Microsoft.Devices.DeviceTelemetry",
subject = "devices/b82bfa90fb/gw-uplink",
dataVersion = "1.0"
}
With the latest offering however, all of this is removed for some reason.
Old documentation with constructor etc (https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.eventgrid.models.iothubdevicetelemetryeventdata.-ctor?view=azure-dotnet
New documentation with no constructor, no setter on the body (DeviceTelemetry is sealed) etc:
https://learn.microsoft.com/en-us/dotnet/api/azure.messaging.eventgrid.systemevents.iothubdevicetelemetryeventdata?view=azure-dotnet
Anyone run into this? I would like to get off the old but I have existing unit tests that logically create TelemetryEventData and send to the function. I see no way of unit testing this ? I have tried mocking IotHubDeviceTelemetryEventData with
_mockHubTelemEventData.setup(c => c.Body).Returns(foo)
but this as well throws me an error of no setter on Body.
Super frustrating.
Other attempts have included creating EventGridEvent() but this as well is missing core functionality as the EventGridEvent.parse won't find any object of type Body.
EventGridEvent[] egEvents = EventGridEvent.ParseMany(BinaryData.FromStream(req.Body));
Mocking code you don't own comes with downsides, and you just one of them. But that's not why you're here. If you want to create instances of IotHubDeviceTelemetryEventData, you can try creating them as JSON and deserialize them. Give this a shot:
using System.Text.Json;
using Azure.Messaging.EventGrid.SystemEvents;
var json = #"
{
""body"":
{
""property"": { ""foo"": ""bar"" }
}
}
";
var eventData = JsonSerializer.Deserialize<IotHubDeviceTelemetryEventData>(json);

How to use enum in AuthorizeAttribute the razor mvc?

I have this enum:
public enum PerfilUsuarioEnum
{
AdministradorSistema = 1,
AdministradorLoja = 2,
Gerente = 3
}
And I want to pass it on my Authorize roles
[Authorize(Roles = PerfilUsuarioEnum.AdministradorLoja + ", " + PerfilUsuarioEnum.Gerente)]
There is some manner to do this?
Roles has to be constant expression such as string. Easiest way is to use cosntant.
public static class PerfilUsuario
{
public const string AdministradorLoja = "AdministradorLoja";
public const string Gerente = "NaviGerentegators";
}
[Authorize(Roles = PerfilUsuario.AdministradorLoja + ", " +
PerfilUsuario.Gerente)]
Great question. Here is what I did...
I decided to make my permissions database driven so I needed a way to convert strings into something "typed" so that I could get compile time warnings and also so I could change the name of the permission in the database and not have to update all of our production code. Since the attributes are string based (so called magic strings), I decided against enumerations and went with a T4 script that read the database and generated a struct for each record. This allowed me to also add things like, a nice display name, details about the permission, and an error message that I could show the user.
Here is a sample permission row after the T4 template runs.
public struct CanViewClaimData
{
// Using const allows the compiler to generate the values in the assembly at compile time and satisfy MVC Authorize Attribute requirements for const strings.
public const System.String Name = "CanViewClaimData";
public const System.String DisplayName = "Can View Claim Data";
public const System.String Description = "The allows users to view claim data";
public const System.String DefaultErrorMessage = "You must have the \"Can View Claim Data\" permission to access this feature.";
}
Then in code I use a sub classed Authorize and mark the Action as such,
[Security.AuthorizedAttribute(Roles = CanViewClaimData.Name, Message = CanViewClaimData.DefaultErrorMessage)]
Then during each automated build and push to our C.I. environment, I run the T4 template as part of the build process to keep the struct strings in sync with the database.
So far this has worked really well and allowed me to give our product owner the ability to edit the permission names, descriptions etc, in the database and without a developer having to be involved.

How to create transform for .msi file using c#

I'm trying to create a transform for .msi file in C#. Here is my code:
public static void CreateTransforms(string original_MSI, string backup_MSI, string MSTpath, string query)
{
File.Copy(original_MSI, backup_MSI, true);
using (var origDatabase = new Microsoft.Deployment.WindowsInstaller.Database(original_MSI, DatabaseOpenMode.ReadOnly))
{
using (var database = new Microsoft.Deployment.WindowsInstaller.Database(backup_MSI, DatabaseOpenMode.Direct))
{
//database.Execute("Update `Property` Set `Property`.`Value` = 'Test' WHERE `Property`.`Property` = 'ProductName'");
database.Execute(query);
database.GenerateTransform(origDatabase, MSTpath);
database.CreateTransformSummaryInfo(origDatabase, MSTpath, TransformErrors.None, TransformValidations.None);
}
}
}
I got the following error : "This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package." in the step create transform summary info. I used "Microsoft.Deployment.WindowsInstaller.dll" library. Any help would be great.
A quick read of this static method looked correct so I created a console app out of it. It works fine for me on my machine. I would look at your calling method and make sure the data being passed is correct. I get really nervous any time I have a method that takes 4 strings as arguments as that leaves a lot to desire in terms of type safety.
when CreateTransforms start, it open database and it does not close it ...
you must commit and close the database before apply a new transform!
database.GenerateTransform(origDatabase, TRANSFORM);
database.CreateTransformSummaryInfo(origDatabase, TRANSFORM, TransformErrors.None, TransformValidations.None);
database.Commit();
database.Close();

Xamarin iOS localization using .NET

I'm trying to use .NET localization in a portable class library for a Xamarin iOS/Android project. I've followed the steps at:
How to use localization in C#
And have code which looks as follows:
string sText = strings.enter_movie_name;
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fr");
sText = strings.enter_movie_name;
lblEnterMovieName.Text = sText;
I've also tried:
ResourceManager resman = new ResourceManager(typeof(MyApplication.strings));
string sText = resman.GetString("enter_movie_name", new CultureInfo("fr"));
I've created strings.resx with enter_movie_name equal to "Enter movie name:" and strings.fr.resx equal to "Entre la movie name:"
However, sText always ends up as "Enter movie name:". I can't seem to get the "Entre la movie name:" version out.
I also saw the post at Cross-platform Localization but couldn't work it out. I also don't want to use the iOS specific version at Localization on Xamarin.iOS as I'd like to be able to get at my strings from a platform independent library.
Can anyone point out where I'm going wrong?
I've created a bit of an ugly solution, but it works. What I've done is made a folder called 'strings' in my Portable Class Library (PCL) and inside that created files called:
strings.resx
strings_fr.resx
strings_ja_JP.resx
I've set all of these as Embedded Resource with custom tool as ResXFileCodeGenerator. This means I have a separate resource DLL for each language.
In iOS I can then get the locale by calling:
string sLocale = NSLocale.CurrentLocale.LocaleIdentifier;
I would guess there's an Android equivalent using Locale but I don't know what it is.
This gives me a string like "ja_JP" or "fr_FR" or "en_GB" (note they're underscores, not dashes). I then use this with the following static class I created to retrieve an appropriate resource manager and get the string from it.
If given a locale aa_BB it first looks for strings_aa_BB, then for strings_aa, then for strings.
public static class Localise
{
private const string STRINGS_ROOT = "MyPCL.strings.strings";
public static string GetString(string sID, string sLocale)
{
string sResource = STRINGS_ROOT + "_" + sLocale;
Type type = Type.GetType(sResource);
if (type == null)
{
if (sLocale.Length > 2) {
sResource = STRINGS_ROOT + "_" + sLocale.Substring(0, 2); // Use first two letters of region code
type = Type.GetType(sResource);
}
}
if (type == null) {
sResource = STRINGS_ROOT;
type = Type.GetType(sResource);
if (type == null)
{
System.Diagnostics.Debug.WriteLine("No strings resource file when looking for " + sID + " in " + sLocale);
return null; // This shouldn't ever happen in theory
}
}
ResourceManager resman = new ResourceManager(type);
return resman.GetString(sID);
}
}
An example of how this would be used (referring to the above code) would be:
string sText = Localise.GetString("enter_movie_name", sLocale);
lblEnterMovieName.Text = sText;
A significant downside of this is that all views will need to have their text set programatically, but does have the upside that the translations can be done once and then reused on many platforms. They also remain separate from the main code in their own DLLs and therefore can be recompiled individually if necessary.
I created a similar solution to the accepted answer but using txt files instead of Resx and nuget ready to go: https://github.com/xleon/I18N-Portable. Blog post here.
Other improvements are:
"anyKey".Translate(); // from anywhere
Automatic detection of the current culture
Get a list of supported translations: List<PortableLanguage> languages = I18N.Current.Languages;
Support for Data Binding in Mvvm frameworks / Xamarin.Forms
etc

how to show publish version in a textbox?

At the moment I am manually updating the version field (textbox) in my application every time I publish it. I am wondering if there is a way to have my application get that data from somewhere and display it in the box for me. I am using VS2012 and I am just unsure of how to achieve that in C#. Below is a screenshot of the VS2012 properties window that I am talking about.
NEW IMAGE:
Don't forget to check if the application is networkdeployed otherwise it won't work in debug mode.
if (ApplicationDeployment.IsNetworkDeployed)
{
this.Text = string.Format("Your application name - v{0}",
ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString(4));
}
Try this:
using System.Deployment.Application;
public Version AssemblyVersion
{
get
{
return ApplicationDeployment.CurrentDeployment.CurrentVersion;
}
}
Then the caller to the getter property can de-reference the Major, Minor, Build and Revision properties, like this:
YourVersionTextBox.Text = AssemblyVersion.Major.ToString() + "."
+ AssemblyVersion.Minor.ToString() + "."
+ AssemblyVersion.Build.ToString() + "."
+ AssemblyVersion.Revision.ToString();
Also we can use overloadedToString of System.Version
using System.Deployment.Application;
public Version AssemblyVersion
{
get
{
return ApplicationDeployment.CurrentDeployment.CurrentVersion;
}
}
YourVersionTextBox.Text = AssemblyVersion.ToString(1); // 1 - get only major
YourVersionTextBox.Text = AssemblyVersion.ToString(2); // 1.0 - get only major, minor
YourVersionTextBox.Text = AssemblyVersion.ToString(3); // 1.0.3 - get only major, minor, build
YourVersionTextBox.Text = AssemblyVersion.ToString(4); // 1.0.3.4 - get only major, minor, build, revision
Method 1 :
You can use this
string version = Application.ProductVersion;
and show the version in your textBox.
Method 2 :
or if you want the version parts separately, you can use this :
System.Version version2 = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
now you have these :
version2.Major;
version2.Minor;
version2.Revision;
version2.Build;
and you can use them like this
string versionString= (String.Format("{0}.{1}.{2}.{3}", version2.Major, version2.Minor, version2.Revision, version2.Build));
If you get an error of ApplicationDeployment, then you can try this:
For global version accessing through Program, declare inside Program class:
private static Version version = new Version(Application.ProductVersion);
public static Version Version
{
get
{
return version;
}
}
Now you have Program.Version anywhere available in the program and you can use it to get version information like this:
LabelVersion.Text = String.Format("Version {0}.{1}",
Program.Version.Major.ToString(),
Program.Version.Minor.ToString());

Categories