I am working on script which uses powershell to add, remove ports to the specific printer and it works really nice! App works on 4.6.2 framework and I am referencing System.Management.Automation.dll from nuget
Microsoft.PowerShell.5.1.ReferenceAssemblies.1.0.0
The problem is that in my logs I am getting exceptions from System.Management.Automation.PSInvalidCastException like that:
System.Management.Automation.PSInvalidCastException: Cannot convert the "Microsoft.PowerShell.Cmdletization.GeneratedTypes.Printer.RenderingModeEnum" value of type "System.String" to type "System.Type".
at System.Management.Automation.LanguagePrimitives.ConvertStringToType(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable) |
System.Management.Automation.PSInvalidCastException: Cannot convert the "Microsoft.PowerShell.Cmdletization.GeneratedTypes.Printer.PrinterStatus" value of type "System.String" to type "System.Type".
at System.Management.Automation.LanguagePrimitives.ConvertStringToType(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable) |
System.Management.Automation.PSInvalidCastException: Cannot convert the "Microsoft.PowerShell.Cmdletization.GeneratedTypes.Printer.TypeEnum" value of type "System.String" to type "System.Type".
at System.Management.Automation.LanguagePrimitives.ConvertStringToType(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable) |
System.Management.Automation.PSInvalidCastException: Cannot convert the "Microsoft.PowerShell.Cmdletization.GeneratedTypes.Printer.DeviceTypeEnum" value of type "System.String" to type "System.Type".
at System.Management.Automation.LanguagePrimitives.ConvertStringToType(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable) |
System.Management.Automation.PSInvalidCastException: Cannot convert the "Microsoft.PowerShell.Cmdletization.GeneratedTypes.Printer.WorkflowPolicyEnum" value of type "System.String" to type "System.Type".
at System.Management.Automation.LanguagePrimitives.ConvertStringToType(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable) |
System.Management.Automation.PSInvalidCastException: Cannot convert the "Microsoft.PowerShell.Cmdletization.GeneratedTypes.PrinterConfiguration.DuplexingModeEnum" value of type "System.String" to type "System.Type".
at System.Management.Automation.LanguagePrimitives.ConvertStringToType(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable) |
System.Management.Automation.PSInvalidCastException: Cannot convert the "Microsoft.PowerShell.Cmdletization.GeneratedTypes.PrinterConfiguration.PaperSizeEnum" value of type "System.String" to type "System.Type".
at System.Management.Automation.LanguagePrimitives.ConvertStringToType(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable) |
System.Management.Automation.PSInvalidCastException: Cannot convert the "Microsoft.PowerShell.Cmdletization.GeneratedTypes.PrintJob.JobStatus" value of type "System.String" to type "System.Type".
at System.Management.Automation.LanguagePrimitives.ConvertStringToType(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable) |
System.Management.Automation.PSInvalidCastException: Cannot convert the "Microsoft.PowerShell.Cmdletization.GeneratedTypes.TcpIpPort.ProtocolEnum" value of type "System.String" to type "System.Type".
at System.Management.Automation.LanguagePrimitives.ConvertStringToType(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable) |
System.Management.Automation.PSInvalidCastException: Cannot convert the "Microsoft.PowerShell.Cmdletization.GeneratedTypes.WSDPrinterPort.DiscoveryMethodEnum" value of type "System.String" to type "System.Type".
at System.Management.Automation.LanguagePrimitives.ConvertStringToType(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable) |
System.Management.Automation.PSInvalidCastException: Cannot convert the "Microsoft.PowerShell.Cmdletization.GeneratedTypes.PrinterProperty.PropertyTypeEnum" value of type "System.String" to type "System.Type".
at System.Management.Automation.LanguagePrimitives.ConvertStringToType(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable) |
I am adding commands, parameters and calling powershell like this:
using (var powerShell = Create())
{
powerShell.AddCommand("Get-PrinterPort").AddParameter("Name", "somePortName").AddStatement();
var output = powerShell.Invoke();
}
Has anyone an idea how to get rid of these errors?
I was trying with few versions of System.Management.Automation.dll but I am limited by System.Runtime 4.1.2 version.
Related
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.CurrencySymbol = "$";
var result1 = decimal.Parse("$123456", NumberStyles.Any, nfi).Dump(); // this works well
var result2 = Convert.ChangeType("$123456", typeof(decimal), nfi); // this doesn't work
I need Convert.ChangeType() to accept currency, is it possible? Tried setting NumberFormatInfo but looks like it ignores currency values.
Convert is a static class and also ChangeType() is a static method, so you can not override them.
Even if this is not exactly what you have asked for, however, you may create your own class change the way you want it to work for decimal (and any others) and use Convert.ChangeType() as default for other types:
public static class MyConvert
{
public static object? ChangeType(object? value, Type conversionType, IFormatProvider provider)
{
if (conversionType == typeof(decimal))
return decimal.Parse(value.ToString(), NumberStyles.Any, provider);
else
return Convert.ChangeType(value, conversionType, provider);
}
}
Now the following code would work as you expect:
var result2 = MyConvert.ChangeType("$123456", typeof(decimal), nfi);
I'm working on Universal Store app. I've made this converter:
public object Convert(object value, Type targetType, object parameter, string language)
{
string stringDate = (string)value;
IFormatProvider culture = new CultureInfo( language );
DateTime date = DateTime.Parse(stringDate, culture);
return date.LongTimeString();
}
but Method LongTimeString is not recognized. This method is deprecated? Any solution? Thanks
DateTime doesn't have a method as LongTimeString. I think you looking for ToLongTimeString method.
return date.ToLongTimeString();
Mabe you are mixing this method with LongTimePattern property of DateTimeFormatInfo.
It's not deprecated, just not part of the WinRT API.
The solution is something like
return date.ToString("D");
But I'm not sure what exactly is supported.
myl.Add(AllNews[i].original_time);
myl is a List type string and also original_time is a string.
For example now original_time contain the string: "D140707T2149"
And now I want to convert this string to be with only numbers without the D and T and to format: yyyyMMddHHmm without seconds.
And then in the end to build a string like this:
string results = myTime.ToString("hh:mm דווח במקור בתאריך : dd.MM.yy : שעה");
The hebrew words stay the same only yhe date and time iwll change each time.
This is what i tried to do:
IFormatProvider provider = CultureInfo.InvariantCulture;
DateTime myTime = DateTime.ParseExact(AllNews[i].original_time, "DyyMMddThhmm", provider);
string results = myTime.ToString("hh:mm דווח במקור בתאריך : dd.MM.yy : שעה");
But I'm getting exception on the line:
DateTime myTime = DateTime.ParseExact(AllNews[i].original_time, "DyyMMddThhmm", provider);
String was not recognized as a valid DateTime
Then I tried first to remove the D and T from the string:
AllNews[i].original_time = Regex.Replace(AllNews[i].original_time, "[^0-9]", "");
IFormatProvider provider = CultureInfo.InvariantCulture;
DateTime myTime = DateTime.ParseExact(AllNews[i].original_time, "yyyyMMddHHmm", provider);
string results = myTime.ToString("hh:mm דווח במקור בתאריך : dd.MM.yy : שעה");
But again same exception as before:
System.FormatException was unhandled
HResult=-2146233033
Message=String was not recognized as a valid DateTime.
Source=mscorlib
StackTrace:
at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)
at ScrollLabelTest.ListsExtractions.listtostringlist(List`1 lnl, List`1 myl) in ListsExtractions.cs:line 345
at ScrollLabelTest.ListsExtractions.Ext(String filename) in
ListsExtractions.cs:line 220
at ScrollLabelTest.Form1..ctor() in Form1.cs:line 127
at ScrollLabelTest.Program.Main() in Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
You need uppercase HH for the hours since you are using a 24h clock(21) in:
string original_time = "D140707T2149";
So this works:
DateTime myTime = DateTime.ParseExact(original_time, "DyyMMddTHHmm", CultureInfo.InvariantCulture);
See: http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx#HH_Specifier
You need to use your D and T with literal string delimiter as ' or ".
Also you need to use HH specifier instead of hh specifier because your hour is 24-hour clock.
DateTime myTime = DateTime.ParseExact("D140707T2149" ,
"'D'yyMMdd'T'HHmm",
CultureInfo.InvariantCulture);
Console.WriteLine(myTime);
Here a demonstration.
hh specifier is for 01 to 12 (12-hour clock), HH specifier is for 00 to 23.
I am calling a IValueConverter class via code behind, but I am not sure what to put in the Type targetType parameter. The object is string but using that give me 'invalid expression term 'string'`
my code to call the converter
secondConverter.Convert(score, string, null, CultureInfo.CurrentCulture);
The converter class
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
TimeSpan ts = new TimeSpan(0, 0, (int)value);
return String.Format("{0:D2}:{1:D2}:{2:D2}",
ts.Hours,
ts.Minutes,
ts.Seconds);
}
You can put typeof(string) instead of string, but your converter does not seem to use or validate target type, so you can put just about anything there, including null.
Generally, your converter should at least validate that target type is string and throw exception if it is not.
You'll want
secondConverter.Convert(score, typeof(string), null, CultureInfo.CurrentCulture);
to actually make it a parameter of type Type.
i am converting strings to values using a culture specified to me as a IFormatProvider.
i am trying to figure out which culture they gave me.
i realize that IFormatProvider doesn't necessarily have to correspond to a System.Globalization.Culture, but it did.
So how can i get its name?
The CultureInfo class implements IFormatProvider so you may try casting:
IFormatProvider provider = ...
CultureInfo ci = provider as CultureInfo;
if (ci != null)
{
string name = ci.DisplayName;
...
}