Convert webcontrols.ListItem to an object of a class - c#

when I try to cast a list item as an object, I get the following. "Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'ASPGigManager2.GigOpportunity'"
Is there anyway you can do this? Here is my code:
GigOpportunity gigOpportunity;
gigList.removeGig((GigOpportunity)lstGigs.SelectedItem);
I have tried to go the long way round and convert it to string but I still get a conversion error, string to GigOpportunity.
GigOpportunity gigOpportunity;
string test;
test = Convert.ToString(lstGigs.SelectedItem);
gigOpportunity = test;

Its as it says, you cannot convert a ListItem to GigOpportunity. And since this is ASP.NET, your original object no longer exists inside the list control. So, during your initial binding, set the DataValueField property to a unique value that identifies each gig (such as a primary key).
Then, on a callback, you have to find your original gig again. For example:
var selectedValue = lstGigs.SelectedValue;
var gig = gigList.Where(x => x.SomeKeyValue == selectedValue).Single();
gigList.Remove(gig);
Better yet, turn you gigList into a dictionary who's key is the same key you used as the value. Then, all you have to do is
gigDict.Remove(lstGigs.SelectedValue);

Related

How to Update KTA RunTimeField with an object?

I am trying to update an object (Generic List object) to RuntimeFiledCollection. When I try to update using the following code, I am getting always Serialization error :(
//My object which need to update set with the documentRuntimeField value
List<docInfo> docInfoList = new List<docInfo>
docInfo = new docInfo { ID = "11233", PageNumber = 1, text ="MyOwnText"};
docInfoList.Add(docInfo);
// Construct DOcument RuntimeFields Collection
var docRunTimeCollection = new CaptureDocumentService.RuntimeFieldCollection();
var docRunTimeField = new CaptureDocumentService.RuntimeField
{ Name = "FieldName", Value = docInfoList };
docRunTimeCollection.Add(docRunTimeField);
captureDocumentServiceClient.UpdateDocumentFieldValues(sessionId, null, validDocumentId, docRunTimeCollection);
I always get sterilization error as shown below. Can someone give me an example how to update document field values with an object. Any help ?
Error : There was an error while trying to serialize parameter http://www.kofax.com/agilityservices/sdk:runtimeFields.InnerException message was System.Collections.Generic.List
For RuntimeField class, you can see the the Value property is of type Object, but that is misleading, because it is not an arbitrary container. It takes the type that you defined for that field in your Extraction Group. But essentially that just means it will take a DateTime for a Date field or numeric types for a Number field, and anything else would be casted to string.
If you actually using a Table Field, then you cannot use the API to set the contents of the entire table. You would instead set the RuntimeField.TableRow and RuntimeField.TableColumn properties to use the API to set individual cells.

Handling nonexistant JSON tokens in JSON.Net how to return default instead of throwin exception

I have a problem, under http://www.pathofexile.com/api/public-stash-tabs link there is a huge API that returns a JSON string. Many of fields in this JSON are optional, that means they only appear if there is value present.
So theoretical "Item1" can have "abyssJewel" property but
"item2" doesnt have to have "abyssJewel" property
When i try to query this JSON with JSON.Linq like this
AbyssJewel = (bool)item["abyssJewel"];
in the case of Item1 everything is good and it returns proper value
but in case of Item2 i get exception "InvalidOperationException, Cannot access child value on Newtonsoft.Json.Linq.JProperty"
I understand its because for Item2 no abyssJewel property in JSON exists so it throws exception.
My question is this, how can i handle it so that instead of throwing exception it would return a default or null value for this particular field?
I have tried playing with Activator but couldnt make anything working on my own. Any tips?
im instantiating it like this:
apiPages.Add(new Page
{
Next_Change_Id = (string)jsonObject["next_change_id"],
Stashes = jsonObject["stashes"].Select(stash => new Stash
{
AccountName = (string)stash["accountName"],
StashName = (string)stash["stash"],
StashType = (string)stash["stashType"],
Public = (bool)stash["public"],
LastCharacterName = (string)stash["lastCharacterName"],
UniqueId = (string)stash["id"],
Items = stash.Select(item => new Item
{
AbyssJewel = (bool)item["abyssJewel"],
...tl;dr...
Instead of casting directly you should try to use the TryParse() method from the Boolean class, if something goes wrong it must return false. See here
Hope it will fix your problem.

How can i access Structure property that is inside Hashtable? [duplicate]

This question already has answers here:
Modify Struct variable in a Dictionary
(5 answers)
Closed 7 years ago.
I have the following code that will modify a property inside a structure, and the structure is inside a hash table. Each item in hash table has key of (Int) data type and key of (struct Bag), here is the code i have:
struct Bag {
string apple_type;
string orange_type;
};
// Make a new hashtable that will have a key of (int) data type, value of (Bag)
public static Hashtable bags = new Hashtable();
Then i have a method that will read data from a data base reading rows and adding as long there is a row it will add an item (bag(object)) to the hashtable:
public void initHashtbl(){
OleDbConnection db_connector = new OleDbConnection(connection_string);
// Open connection to oracle
db_connector.Open();
OleDbCommand sql_commander = new OleDbCommand(sql_statement, db_connector);
OleDbDataReader data_Reader = sql_commander.ExecuteReader();
// Read data from sql db server and store it in memory ...
Bag tempBag = new Bag();
// row counter used for list view
int row_counter = 0;
while (data_Reader.Read()) { // Keep reading data from memory until there is no row
tempBag.apple_type = data_Reader[0].ToString();
bags.Add(row_counter, tempBag);
row_counter++;
}
for(int bag_item=0;bag_item < bags.Count;bag_item++){
// Get orange type value from another method that uses another sql statement from another table in db ..
((bag) bags[bag_item]).orange_type = getOrangeType(((bag) bags[bag_item]).apple_type);
}
}
How can i access the property of structure that is already inside hash table at later time if i wanted to access it?
Edit:
I'm getting this error:
"Cannot modify the result of an unboxing conversion."
Dictionary will not allow me to modify that directly
Neither will a Hashtable. This has nothing to do with Hashtable vs Dictionary. The problem is that your "value" in either case is a value type, so you can't modify it directly within the collection. If you really need a struct, then you'll have to create a new value and put it back into the hashtable:
bags.Add(1, new Bag() {apple_type="apple1",orange_type="orange1"});
//((Bag)bags[1]).apple_type="apple2";
var bag = (Bag)bags[1];
bag.apple_type = "appple2";
bags[1] = bag;
But mutable structs are generally bad, so I would either get the value of the struct right the first time (rather than modifying it ourside of the initial load loop) :
// row counter used for list view
int row_counter = 0;
while (data_Reader.Read()) { // Keep reading data from memory until there is no row
{
var appleType = data_Reader[0].ToString();
Bag tempBag = new Bag() {
apple_type = appleType,
orange_type = getOrangeType(appleType)
};
bags.Add(row_counter, tempBag);
row_counter++;
}
or use a class.
Note that the same code works exactly the same way whether you use a Hashtable or a Dictionary.
Also, since your "key" is just an incrementing number (and not tied to the value at all), you could just as well use a List<Bag> and access the items by index.
This code worked for me to read an item:
string orangeType = ((Bag) bags[0]).orange_type;
To modify an item, I think you must create a new Bag and replace the existing one like this:
bags[0] = newBag;
If you try to modify the properties of a bag in the HashTable, then you get the error you reported above.
Because of how value types work, the boxed Bag is a copy of the original, and "unboxing" it by casting back to Bag creates yet another copy. From the C# language spec:
When a value of a value type is converted to type object, an object
instance, also called a “box,” is allocated to hold the value, and the
value is copied into that box. Conversely, when an object reference is
cast to a value type, a check is made that the referenced object is a
box of the correct value type, and, if the check succeeds, the value
in the box is copied out.
Modifying the copy wouldn't change the original anyway, so it wouldn't make much sense to allow it.
Corrections:
To fix your error and to allow modifications to your HashTable of Bag's you should change your value type to reference type:
public class Bag
{
public string apple_type { get; set; }
public string orange_type { get; set; }
};

Calling the property names of a dynamic property "ints": can't call property

I am assigning property names of a dynamic object as ints in string form. The int value represents an int ID in a database I am using. However I am stuck on how to retrieve the value assigned to the property as shown below:
dynamic test = new ExpandoObject()
IDictionary<string, object> proxyFiler = test as IDictionary<string, object>;
proxyFiler["four"] = 4;
proxyFiler["5"] = 5;
int r = test.four; // Works
int s = test.5; // Doesn't work
A method which reads the database will return an "int" and I would like to be able to access the property value with that property name.
To expand on this: what if I wanted to do a linq query to sort out a list of dynamic objects according to a property name? In this case I need to get the propertyName which I have retrieved as a string e.g. "15":
return disorderedList.OrderBy(o => o.propertyName).ToList();
Does anyone know a simple solution to this problem or do you recommend a different approach? Thanks.
In order for dynamic to work in this way, the key has to follow the rules for valid identifier names in C# (the rules are specified in this outdated MSDN page, but also in the C# language specification). A single number (5) is not an allowed identifier name, which is why that doesn't work.
Note that you can still retrieve the value by using the type as a dictionary, in a similar manner to how you populated it.
As for your second example - you are never using value, so it has no effect. It's the same as just writing int r = test.four;
Edit:
I believe, given your approach, you'd need to cast to a dictionary:
return disorderedList
.OrderBy(o => ((IDictionary<string, object>)o)[propertyName]).ToList();

How to handle type “Object {System.Collections.Generic.List<object>}”

This is my first time encountering with such an object.
>Link of image of my local window during debug<
So to put it very simply, how do I access the value for CardNO or ItemID, which is 296 and 130 respectively when the only methods 'test' give are exactly like a normal object and I don't know what to cast it to. I can't even do this 'test[0]'.
This is where 'test' comes from:
private void ListBoxIssue_OnDragEnter(object sender, DragEventArgs e)
{
var test = DragDropPayloadManager.GetDataFromObject(e.Data, typeof(CommsItem));
}
Use
var item = (CommsItem)((List<object>)test).FirstOrDefault();
Be sure to check first if test is an instance of List<object> before casting, and if test[0] is an instance of CommsItem.
You need to cast your List<Object> to List<CommsItem>.
Example:
var test = DragDropPayloadManager.GetDataFromObject(e.Data, typeof(CommsItem)).Cast<CommsItem>().ToList();
Or cast each individual element:
CommsItem element = (test[0] as CommsItem);
Which will return the element casted to CommsItem, unless it is not of or derived of that type, in which case it will return null.
So to answer your question, you can access them as:
string CardNO = (test[0] as CommsItem).CardNO;
or
var test = DragDropPayloadManager.GetDataFromObject(e.Data, typeof(CommsItem)).Cast<CommsItem>().ToList();
string CardNO = test[0].CardNO;
(If you use the first method, you do not need the cast)
What you are doing is casting your List<object>, test, to a List<CommsItem>, that you can use to access the properties, or simply casting each item.
More simply:
var item = ((List<object>)test).Cast<CommsItem>().FirstOrDefault();
If your list is not a list of CommsItem, then you'll get an empty list back. FirstOrDefault() ensures that you get the first item only, and if there is no first item, then the default value for the item (for a reference object, this would be null).

Categories

Resources