Specified cast is not valid - winforms

I tried all my best to cast the value but some how i keep getting this exception. Hope some one will guide me in the right path.
Here is my code
This type from service
public enum ChannelCodeType {
/// <remarks/>
A1,
/// <remarks/>
A2,
/// <remarks/>
A3,
/// <remarks/>
A4,
}
in my winform i have a list box that generate all these channels ,i try to cast the selected channels in the list box and pass it to the channel type but it gives me a hard time.
ChannelCodeType[] ChannelCodes;
ChannelCodes=lbSearch.SelectedItems.ToString().Cast<ChannelCodeType>().ToArray();
then i tried like below also failed
string[] destination = new string[lbSearch.Items.Count];
lbSearch.Items.CopyTo(destination, 0);
ChannelCodes = destination.Cast<ChannelCodeType>().ToArray();
in both way it keeps complaining about cast is not valid.

ChannelCodes = destination.Select(e => (ChannelCodeType)Enum.Parse(typeof(ChannelCodeType),e)).ToArray();
Try something like the above.
The problem with your current approach is that you can't cast a string to an enum directly. You have to parse it.

Related

How to find a specific field from a genetic List object in wpf

I am trying to create a generic class for finding duplicate values for different class.
I am casting each list to an object and passing it as parameter like this
List<StudentModel1> a = new List<StudentModel1>();
List<StudentModel2> b = new List<StudentModel2>();
List<StudentModel3> c = new List<StudentModel3>();
List<object> obj = a.Cast<object>().ToList();//like this
public bool Duplicate(List<object> obj, string Fieldname, string Name)
{
if (obj.Any(x => x.Fieldname.Contains(Name))) { return true; } else { return false; }
}/// something like this;
here i am passing fieldname propery ,string name and object for finding duplicate and return a bool.How to access field name in linq.
please help how to acheive this.
thanks.
If I understand your question correctly, you have 3 different versions of a class: StudentModel1, StudentModel2 and StudentModel3 and you want to be able to compare lists of them. You are casting them to Object so that you can pass any any version of that class to your Duplicate method.
Assuming the above is correct, what you need is inheritance. If that's not something your familiar with you should definitely read up on it.
Consider the following:
class StudentModelBase
{
public string SomeProperty { get; set; }
}
class StudentModel1 : StudentModelBase
{
}
class StudentModel2 : StudentModelBase
{
}
class StudentModel3 : StudentModelBase
{
}
If your Duplicate method should be able to handle any of the "StudentModel" classes, then that means the information needed to tell if there are duplicates must be common to all three versions of that class. The properties and fields which store that information should be moved into StudentModelBase. Then, instead of casting to Object you should cast to StudentModelBase.
Your cast becomes:
List<StudentModelBase> base = a.Cast<StudentModelBase>().ToList();
And your Duplicate method becomes something like the following:
public bool Duplicate(List<StudentModelBase> obj, string Name)
Notice I left out Fieldname because if this is implemented correctly you shouldn't need to pass that as a parameter. You should just be able to access the need members of StudentModelBase like any normal variable, since they should be the same for all versions of "StudentModel".

Is it possible to pass Java-Enum as argument from cucumber feature file

I am currently using selenium with Java,And want to implement cucumber to make test script more readable.
Currently facing issue while passing argument to java method where Enum is expected as parameter.
I would also like to know if there are any other known limitations of cucumber-java before migrating current framework.
The answer is: Yes
You can use all kind of different types in your scenario: primitive types, own classes (POJOs), enums, ...
Scenario :
Feature: Setup Enum and Print value
In order to manage my Enum
As a System Admin
I want to get the Enum
Scenario: Verify Enum Print
When I supply enum value "GET"
Step definition code :
import cucumber.api.java.en.When;
public class EnumTest {
#When("^I supply enum value \"([^\"]*)\"$")
public void i_supply_enum_value(TestEnum arg1) throws Throwable {
testMyEnum(arg1);
}
public enum TestEnum {
GET,
POST,
PATCH
}
protected void testMyEnum(TestEnum testEnumValue) {
switch (testEnumValue) {
case GET:
System.out.println("Enum Value GET");
break;
case POST:
System.out.println("Enum Value POST");
break;
default:
System.out.println("Enum Value PATCH");
break;
}
}
}
Let me know how you are doing. I could try to help you.
This youtube lecture of about 11 minutes gives a good way of doing it.
https://www.youtube.com/watch?v=_N_ca6lStrU
For example,
// enum, obviously in a separate file,
public enum MessageBarButtonType {
Speak, Clear, Delete, Share
}
// method for parameter type. if you want to use a different method name, you could do #ParameterType(name="newMethodName", value="Speak|Clear|Delete|Share") according to the video.
#ParameterType("Speak|Clear|Delete|Share")
public MessageBarButtonType MessageBarButtonType(String buttonType) {
return MessageBarButtonType.valueOf(buttonType);
}
// use like this. the name inside {} should match the name of method, though I just used the type name.
#Then("Select message bar {MessageBarButtonType} button")
public void select_message_bar_button(MessageBarButtonType buttonType) {
...
}
First register a transformer based on an ObjectMapper, then you can just use enums as would be expected.
private final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
#DefaultParameterTransformer
#DefaultDataTableEntryTransformer
#DefaultDataTableCellTransformer
public Object defaultTransformer(Object fromValue, Type toValueType) {
JavaType javaType = objectMapper.constructType(toValueType);
return objectMapper.convertValue(fromValue, javaType);
}
Scenario: No.6 Parameter scenario enum
Given the professor level is ASSOCIATE
#Given("the professor level is {}")
public void theProfessorLevelIs(ProfLevels level) {
System.out.println(level);
System.out.println("");
}
public enum ProfLevels {
ASSISTANT, ASSOCIATE, PROFESSOR
}
Source
This is no more supported in latest io.cucumber maven group
https://github.com/cucumber/cucumber-jvm/issues/1393

Test value of a HashSet in a FitNesse table cell?

Using FitNesse with FitSharp (.Net), I've got a property of an object that is a HashSet of an enum, e.g.
public enum Fubar { Foo, Bar }
public class Test
{
public HashSet<Fubar> SetOfFubar { get; set; }
}
I'd like to test it simply, for example in an array fixture like so:
|MyArrayFixture|
|SetOfFubar|
|Foo|
|Foo,Bar|
|Bar|
||
This simply results in all rows marked missing & red and a set of surplus rows showing something like:
System.Collections.Generic.HashSet`1[MyNamespace.Fubar] surplus
What's the easiest way to get FitNesse with FitSharp (.Net) to understand HashSets?
You can write a parse operator. Here's a little example from http://fitsharp.github.io/Fit/WriteOurOwnCellOperator.html that parses the string"pi" into a numeric value.
using fitSharp.Fit.Operators;
using fitSharp.Machine.Engine;
public class ParsePi: CellOperator, ParseOperator<Cell> {
The CanParse method override determines which cells are processed by
our operator. We check for "pi" in the cell and also that we are
working with a numeric type. This preserves normal behavior if we're
using "pi" as a string input or expected value.
public bool CanParse(Type type, TypedValue instance, Tree<Cell> parameters) {
return type == typeof(double) && parameters.Value.Text == "pi";
}
Overriding the Parse method changes the behavior when the cell is
parsed to create an input or an expected value.
public TypedValue Parse(Type type, TypedValue instance, TreeTree<Cell> parameters) {
return new TypedValue(System.Math.PI);
}
}

Collection is empty when returning from JAX-RS/CXF service

I have a service method defined as:
public JaxbList<Deal> getDeal() {
List<Deal> deals = new ArrayList<Deal>();
Deal type = new Deal();
type.setDealID(1);
type.setName("June Discounts");
deals.add(type);
JaxbList list = new JaxbList(deals);
System.out.println("List size -> " + list.getList().size());
return list;
}
My client is defined as:
WebClient client = WebClient.create("....");
JaxbList deals = client.path("exampleservice/getDeal")
.accept("application/xml").get(JaxbList.class);
List<Deal> types = deals.getList();
When I print out the size of the collection in the service method, the result comes back as 1. But, the size of my 'types' list from the client is 0. When I open in a browser, the 1 deal is displayed. So, this issue seems to be my client. I'm not sure where though.
Ideas?
Here is my JaxbList class:
public class JaxbList<T>{
protected List<T> list;
public JaxbList(){}
public JaxbList(List<T> list){
System.out.println("Setting list...");
this.list=list;
}
#XmlElement(name="Item")
public List<T> getList(){
return list;
}
}
As mentioned above by KasunBG your public JaxbList(List<T> list) constructor is never called by JAXB. The default no-arg one is used instead (see some discussion at What JAXB needs a public no-arg constructor for?). Actually Java compiler should complain about this situation with two constructors and "never initialized field list".
The solution is to introduce a setList() setter and throw a runtime exception from a no-arg constructor.

Create a thumbnail and then convert to byte array

I'm having a heck of a time with creating thumbnails and then converting them into a byte array. I've tried three methods, and all 3 times I get an error.
The first was using Bitmap.GetThumbnailImage, which I have used in the past and then saved directly into Response.OutputStream
The second was using System.Drawing.Graphics with DrawImage(). Still no go.
The third was just to create a new bitmap, pass in the old bitmap, and set the new size. Same error.
Value cannot be null.
Parameter name: encoder
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: encoder
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentNullException: Value cannot be null.
Parameter name: encoder]
System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) +615244
Here is the code for my method. Maybe someone will see what I'm doing wrong. In case you aren't sure about GetThumbSize, it's simply a method that takes in the image size and the maximum thumb size and then computes an actual size to preserve the aspect ratio.
public static System.Drawing.Image.GetThumbnailImageAbort thumbnailCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
public static bool ThumbnailCallback()
{
return false;
}
/// <summary>
///
/// </summary>
/// <param name="image"></param>
/// <param name="size"></param>
/// <remarks>
/// This method will throw a AccessViolationException when the machine OS running the server code is windows 7.
/// </remarks>
/// <returns></returns>
public static byte[] CreateThumbnail(byte[] imageData, Size size)
{
using (MemoryStream inStream = new MemoryStream())
{
inStream.Write(imageData, 0, imageData.Length);
using (System.Drawing.Image image = Bitmap.FromStream(inStream))
{
Size thumbSize = GetThumbSize(new Size(image.Width, image.Height), size);
//do not make image bigger
if (thumbSize.Equals(image.Size) || (image.Width < size.Width || image.Height < size.Height))
{
//if no shrinking is ocurring, return the original bytes
return imageData;
}
else
{
using (System.Drawing.Image thumb = image.GetThumbnailImage(thumbSize.Width, thumbSize.Height, thumbnailCallback, IntPtr.Zero))
{
using (MemoryStream outStream = new MemoryStream())
{
thumb.Save(outStream, thumb.RawFormat);
return outStream.ToArray();
}
}
}
}
}
}
This line is throwing the error:
thumb.Save(outStream, thumb.RawFormat);
Any ideas? Thanks for the help!
I think the problem may be the original image's encoding. IIRC, Save(stream, format) results in a call to Save(stream, encoder, params), with the encoder being taken from the format; which in your case is the original format of the image.
According to the Community Content for the Save method, some formats will not translate well into an appropriate encoder.
I would suggest you specify the encoder yourself, using some standard format like PNG.
Try:
thumb.Save(outStream, ImageFormat.Png, null); // optionally add encoder parameters here, like quality or luminescence
If what you are trying to do is save it in a Raw format you can try the following, as in my case it works when the original image format is a supported one:
try
{
thumb.Save(outStream, img.RawFormat);
}
catch (System.ArgumentNullException)
{
thumb.Save(outStream, ImageFormat.Png);
}

Resources