Is there a way to check if your session variable contains something... Just like a list has a method "Contains". Is there something similar to that? Some method or something?
Hi you can try casting your session so it can have a type for example
var listofperson = Session["ListofPerson"] as List<string>;
var hasGeorge = listofperson.Contains("George");
When you retrieve items from Session, they are of type System.Object. This means that you don't get any of the actual methods available for the object's real type. You can do so by casting it to the correct type. In this case, it sounds like you're storing a List<string>. So we can use the as operator. If the object is not of that type or was null to begin with, myList will null. Otherwise it will be of the type you specify.
List<string> myList = Session["myKey"] as List<string>();
if(myList == null)
{
//either Session["myKey"] was null or the object wasn't a List<string>
}
else
{
if(myList.Contains("fuzzy puppies"))
{
//your list contains fuzzy puppies
}
else
{
//your list doesn't contain fuzzy puppies
}
}
Calling .ToString() on an object gives you different results based on the object type. The default behavior is to print out the type of the object. But types can override this behavior. For example, calling .ToString() on a string just gives you the string itself. Calling .ToString() on an object that represents some XML might give you the XML as a string. Since List<string> doesn't override the default behavior of System.Object.ToString(), it just prints out "System.Collections.Generic.List`1[System.String]"
First, check if Session["yoursession_var"] is null. Then cast to List(). Then use Exists(), as described here: how to use Exist in List<string> in C#
Related
I have a plain textfield in Tridion that can have multiple values. The itemtype is a SingleLineTextField.
In the TBB code I have the following (removed the non-essential parts):
ItemFields itemFields = new ItemFields(folder.Metadata, folder.MetadataSchema);
foreach (ItemField itemField in itemFields)
{
string itemFieldValue = string.Empty;
switch (Utilities.GetFieldType(itemField))
{
case FieldType.SingleLineTextField:
itemFieldValue = itemField.ToString();
break;
}
}
Now the result in case of two entries is just two strings with a character line break in it.
String A
String B
The method used is a generic one, which also works on other fields, so I was looking for some way to find out if a SingleLineTextField has more values in it.
You can cast the field to a SingleLineTextField type, then iterate through the Values collection, something along these lines:
SingleLineTextField field = (SingleLineTextField)itemField;
foreach(string value in field.Values)
{
// do something with value
}
// or if all you want is the count of values
int i = field.Values.Count;
Firstly, I would advise against relying on the ToString() method on objects unless it is specifically documented. In this case it works with the abstract class ItemField, but this may not always be the case.
The TOM.Net API only defines Definition and Name properties for ItemField, so you need to cast your ItemField object to something more specific.
the TextField abstract class, which SingleLineTextField inherits from, defines a ToString() method, but also Value and Values properties, which are much better suited to what you're trying to do. Looking at the documentation, we can see that Values will give us an IList<String> of the values, even if your field is not multi-valued. Perfect!
So, to answer your question, "I was looking for some way to find out if a SingleLineTextField has more values in it", you need to cast your ItemField as a TextField and check the number of Values it provides, thus:
TextField textField = (TextField)itemField;
// If you need to deal with multi-valued fields separately
if (textField.Values.Count > 1)
{
//Logic to deal with multiple values goes here
}
else
{
//Logic to deal with single valued goes here
}
// Much better... If you can deal with any number of values in a generic fashion
foreach (string value in textField.Values)
{
// Generic code goes here
}
i am getting error "Object reference not set to an instance of an object." my is here,
public class UserProfession
{
public UserProfession()
{
}
public System.String[] Designation
{
get;
set;
}
}
then i am using it like,
UserProfession.Designation[0] =txt_Search.Text.ToString();
Error i mentioned you hopes for your suggestions .
-Thanks
When you make an assignment to an array property, like this:
UserProfession.Designation[0] =txt_Search.Text.ToString();
what you are actually doing is calling the get section for that property... not the set. This returns the object supported the property... the whole object, and not just the index. Index lookup does not happen until after the object is returned. Once you have that object, accessing an index works in the normal way.
You get this specific exception because you have the expression UserProfession.Designation that should return a reference to an array object, but because you never initialize the array there is nothing there when you then try to find reference the 0th element. At this point the framework discovers that the array (your "object reference") is "not set to an instance of an object"... which is just a fancy way of saying it's null.
In other words, you need to have an already existing array to hold the value you want to assign. That means doing something like this:
Designation = new String[10];
public String[] Designation
{
get;
set;
}
However, notice that we never used the set section? So you can simplify that further, like this:
Designation = new String[10];
public String[] Designation {get;private set;}
This will keep client code from completely swapping an entire array out from under your object, but otherwise will provide the full functionality of an array property. If you provide your own backing store for the array, you could even get rid of the setter entirely with no loss of functionality:
private string[] _designation = new string[10];
public string[] Designation {get {return _designation;} }
But let's add one more wrinkle: your desire to assign the to array before initializing it indicates to me that you likely don't really know how big it will be up front. If that's the case, you probably want a collection of some kind instead of an array. A generic List is a convenient and very compatible replacement for an array. That would look like this:
private List<string> _designation = new List<string>();
public List<string> Designation {get {return _designation;}}
You can still access items in that list by index, just like you would with an array. The only difference you need to worry about right now is how you add new items:
UserProfession.Designation.Add(txt_Search.Text);
Also notice that I removed the .ToString() call. Since your .Text property is almost certainly already a string, calling the .ToString() method is just silly.
You will have to initialize the object, before assigning the value. The initialization should be done just once. I have initialized the array size to ten. You can have your own values here. If you want to resize dynamically, you can use ArrayList
int length = 10;
UserProfession.Designation = new System.String[length];
UserProfession.Designation[0] =txt_Search.Text.ToString();
For more information: http://msdn.microsoft.com/en-us/library/aa287601(v=vs.71).aspx
it must initialize the value before we use because, currently, it is null.
you better add the initialization code in the constructor function.
Is it possible to cast a command-line passed string object back to actual object?
I want to do the following, but throwing error can't cast.
Button objPro = (Button) sender;
cProduct cp = (cProduct) objPro.CommandArgument;
If no, then why?
This is what the string holds.
cProduct cpObj = (cProduct)e.Row.DataItem;
Button btnAddProduct = (Button)e.Row.FindControl("btnAddProduct");
if (btnAddProduct != null)
{
btnAddProduct.CommandArgument = cpObj.ToString();
}
You probably can't, because it's a string. It's not a cProduct (whatever that is - consider following .NET naming conventions and naming it Product instead).
Now you could do this if you had a explicit conversion operator in cProduct to create an instance from a string.
You haven't really explained what's in the string, or what's in the type - but if your cProduct type provides a ToString method which contains all the data in a reversible form, then you could easily write a method or a constructor to create the product again:
Product product = new Product(objPro.CommandArgument);
or maybe:
Product product = Product.Parse(objPro.CommandArgument);
You'll have to write that constructor/method, of course.
I would strongly recommend using a constructor or method instead of an operator, just to keep your code clearer - it's very rarely a good idea to write your own conversion operators.
Take a look at CommandArgument on MSDN. The property is a string, when you assign the a value to the property, you aren't casting some complex type to string, you are setting a string value on the property. Can you cast a string back to your object type anyway, regardless of it being a CommandArgument. I doubt it. If the argument is an int you could try int.Parse or similar for other types which have a parse method.
Hello I'd like to ask if you can assign arrays of beans as a form
for example i have a form:
PageForm{
Group[] groupArray;
Group[] getGroupArray(){
return groupArray;
}
void setGroupArray( Group[] groupArray ){
this.groupArray = groupArray;
}
}
Group{
boolean isChecked;
boolean getIsChecked(){
return isChecked;
}
void setIsChecked( boolean ischecked ){
this.isChecked = ischecked;
}
}
id like to access this group array in my jsp.
can i do that using this:
<spring:form>
<spring:checkbox path="groupArray[0].isChecked" />
<spring:checkbox path="groupArray[1].isChecked" />
<spring:checkbox path="groupArray[2].isChecked" />
</spring:form>
What i get is an exception:
org.springframework.beans.NullValueInNestedPathException:
Invalid property 'groupArray[0]' of
bean class [PageForm]: Cannot access
indexed value of property referenced
in indexed property path
'groupArray[0]': returned null
Please help me.
Thanks.
The problem is that Group[] groupArray has not been initialized, so when it goes to the array and looks for the object Group at position 0 it cannot find the Group object.
If you know in advance the number of objects which there can be in the array you can insert as many Group objects as you need in the array groupArray in the constructor of PageForm.
In case you don't know how many object you'll have in the array (because you'll create them from data coming from a form) you'll need to provide a way to create new Group objects when the object has not been instantiated in that position before. I think the easiest way toget this is to change your Group[] array to a List<Group> and use a lazy list like Spring AutoPopulatingList, Apache Commons Collections LazyList or the one provided by the library Guava.
try to change your attribute name maybe myChecked and getter/setter as well
e.g. getChecked and setChecked
im having trouble with the result of a webservice call. When the result comes in and kicks off the resultHandler function i set a break point so i can examine the result. I can see that there are 0 records in the array collection however i can see content so im assuming that the zero is just referring to the first index of the array
the problem happens when i try assign the value to an array collection as follows;
public function resultHandler(event:ResultEvent):void{
var result:ArrayCollection = event.result as ArrayCollection;
the result of this operation is a result var with the value of null. Can anyone explain what could be happening here? thanks a lot
another thing i just noticed is that the result type is mx.utils.ObjectProxy, im expecting an array
If the webservice returns just one element, it will be deserialized as ObjectProxy. You will have to manually convert it into an array.
I'd normally do this after a WS call:
if (event.result is ArrayCollection) {
result = event.result;
}
else {
result = new ArrayCollection([event.result]);
}
Chetan is right -- the cast operation to ArrayCollection is failing, because the source object is not an ArrayCollection. Try this instead:
public function resultHandler(event:ResultEvent):void
{
var ac:ArrayCollection = new ArrayCollection([event.result])
// ...
}
The "as" operator will return null in situations where an exception would occur at runtime -- in your case, casting from ObjectProxy to ArrayCollection. If instead you pass event.result as the sole member of an array (by surrounding it with []), your ArrayCollection will be constructed properly, and you'll be able to retrieve the object normally:
var o:Object = ac.getItemAt(0) as Object;
trace(o.yourObjectProperty.toString());
Hope it helps!
0 records in the array is the length of the array, that actually means 0. If you have something in index 0 of an array, that array has a length of at least 1. It looks like you aren't getting any data back, not even and empty array collection.
The problem in my opinion is that you cannot cast event.result as an array collection, but you have to cast it as an array.
The best practice in this is having a getter and a setter:
private var _acLocation:ArrayCollection=new ArrayCollection;
public function set acLocation(acLocation:ArrayCollection):void{
_acLocation=acLocation;
//do this if you want for exaple to assign the arraycollection to a datagrid dataprovider
dgMyDataGrid.dataProvider=_acLocation;
}
public function get acLocation():ArrayCollection{
return _acLocation;
}
Then in the result handler function of a service call, code
acLocation=new ArrayCollection(event.result as Array);
Hope it helps