How to get the DataSourceId? - asp.net

private SqlDataSource GetDataSource()
{
object o = Session["selectedDataSource"];
DataSourceType dsType = DataSourceType.Gtable;
if (o != null)
dsType = (DataSourceType)o;
switch (dsType)
{
case DataSourceType.tableT:
return DataSourceTID;
case DataSourceType.tableR:
return DataSourceRID;
case DataSourceType.tableC:
return DataSourceCID;
default:
return DataSourceCID;
}
}
For getting the datasourceid I wrote that code.But that gives the error as "Specified cast is not valid".This error is arise at dsType=(DataSourceType)o line.
Please give me any suggextions.

Use enum parse method
http://msdn.microsoft.com/en-us/library/essfb559.aspx
DataSourceType dsType = (DataSourceType) Enum.Parse(typeof(DataSourceType), o);

Related

Linq to XML single or default

I am querying an xml and i am storing the results using singleordefault
var query = from nm in xelement.Descendants("EmployeeFinance")
where (int)nm.Element("EmpPersonal_Id") == empID
select new AllowancePaid
{
gradeTaxId = nm.Element("Allow-GradeTax").Elements("Amount").Attributes("BenListId").Select(a => (int)a).ToList(),
gradeTaxAmt = nm.Element("Allow-GradeTax").Elements("Amount").Select(a => (double)a).ToList()
};
Debug.WriteLine("2");
var resultquery = query.SingleOrDefault();
now this line: var resultquery = query.SingleOrDefault(); works fine if it found in the xml file. However, i have a case where my query will result in a null. If i have no value, it would make an entry in the xml file and my query obviously results in null. My question is how do i cater for this without causing my programe to crash. obviously, singleordefault() doesnt work.
***************** EDITED *************************
I read what everyone said so far and it make sense but i am still having a problem.
if (query.Count() == 0)
{
Debug.WriteLine("NULL");
}
else {
var resultquery = query.SingleOrDefault();
Debug.WriteLine("NOT NULL");
}
OR
if (query == null)
{
Debug.WriteLine("NULL");
}
else {
var resultquery = query.SingleOrDefault();
Debug.WriteLine("NOT NULL");
}
OR
var resultquery = query.SingleOrDefault();
if (resultquery == null)
{
Debug.WriteLine("NULL Result");
}
else
{
Debug.WriteLine("NOT NULL");
}
I am getting a System.NullReferenceException error when the first part of the if statement is true. One user said to do this: var resultquery = query.SingleOrDefault(); then use my if..else statement to do the comparison. However i am getting the error at the point of assign query.singleofdefault() to resultquery. So i am lost.. hope someone can help. thank you
what i am trying to understand is this. the documentation states if the result query is 0 it will give a default value, if it is not, it will be a single value. so why doesnt this give a default value? [taken from the comments]
null is the default value for reference types. Apparently AllowancePaid is a reference type (a custom class).
What is the value you want when the there is no value found.
You could either do:
if (resultquery == null) {
// Logic for No result
} else {
// Logic for result found
}
Or you could force a default value
eg.
var resultquery = query.SingleOrDefault() ?? new AllowancePaid();
UPDATE
From the comments posted it appears that the null reference exception is actually caused within the query itself rather than by the assignment to resultquery and use of later.
This updated query should solve the issue
var query = from nm in xelement.Descendants("EmployeeFinance")
where nm.Element("EmpPersonal_Id") != null
&& (int)nm.Element("EmpPersonal_Id") == empID
&& nm.Element("Allow-GradeTax") != null
&& nm.Element("Allow-GradeTax").Elements("Amount") != null
select new AllowancePaid
{
gradeTaxId = nm.Element("Allow-GradeTax").Elements("Amount").Attributes("BenListId").Select(a => (int)a).ToList(),
gradeTaxAmt = nm.Element("Allow-GradeTax").Elements("Amount").Select(a => (double)a).ToList()
};
var resultquery = query.SingleOrDefault();
if (resultquery == null) {
Debug.WriteLine("NULL Result");
} else {
// Logic here
}

List in asp.net linq query not working

const string keyword = "manoj";
rsp.DataSource = company.GetCompanySearch(keyword);
rsp.DataBind();
public List<Company> GetCompanySearch(string keyword)
{
using (var context = huntableEntities.GetEntitiesWithNoLock())
{
List<Company> query = context.Companies.ToList();
if (!string.IsNullOrEmpty(keyword))
{
keyword = keyword.ToLower();
query = (List<Company>) query.Where(u=>u.CompanyName.Contains(keyword)
|| u.EmailAdress.Contains(keyword)
||u.MasterCountry.Description.Contains(keyword)
||u.MasterIndustry.Description.Contains(keyword)
||u.CompanyDescription.Contains(keyword)
||u.CompanyHeading.Contains(keyword));
}
return query.ToList();
}
}
The following code throwing the following exception:
{"Unable to cast object of type 'WhereListIterator1[Data.Company]' to type 'System.Collections.Generic.List1[Data.Company]'."}
"(List) query.Where()" is equal to "(List) (query.Where())", so this will throw that exception.
Should use query.Where().ToList() but not a explicit cast.
Further, better not put "List query = context.Companies.ToList();" before your "if" statement. In this case, no matter keyword is empty or not, it will query all records into memory and it will cause performance problem.
Can change to below
IQueryable<Company> query = context.Companies; //Remove ToList()
if (!string.IsNullOrEmpty(keyword))
{
keyword = keyword.ToLower();
// Remove cast
query = query.Where(u=>u.CompanyName.Contains(keyword)
|| u.EmailAdress.Contains(keyword)
||u.MasterCountry.Description.Contains(keyword)
||u.MasterIndustry.Description.Contains(keyword)
||u.CompanyDescription.Contains(keyword)
||u.CompanyHeading.Contains(keyword));
}
return query.ToList();

C# Expression Tree: Using TypeAs

My first foray into writing an expression tree in c# is not going too well :). Here's the c# code I'm trying to duplicate
public static object Test<S, D>(S source, Func<D, object> selector )
where S : class
where D : class
{
D derived = source as D;
object retVal = null;
if( derived != null ) retVal = selector(derived);
return retVal;
}
Conceptually, this is intended to take an object and apply a selector to it to return a property of a derived class if the supplied object is of the derived class.
Here's what I've got so far:
public static object OrderByDerivedProperty<S>( S source, Type derivedType, string fieldName )
{
ParameterExpression parameter = Expression.Parameter(typeof(S), "source");
UnaryExpression typeAs = Expression.TypeAs(parameter, derivedType);
ConstantExpression nullConst = Expression.Constant(null);
BinaryExpression isNotNull = Expression.NotEqual(typeAs, nullConst);
ParameterExpression varDest = Expression.Variable(derivedType, "varDest");
ParameterExpression retVal = Expression.Variable(typeof(object), "retVal");
BlockExpression block = Expression.Block(
new[] { varDest, retVal },
Expression.Assign(varDest, typeAs),
Expression.Condition(
isNotNull,
Expression.Assign(retVal, Expression.Property(varDest, fieldName)),
Expression.Assign(retVal, nullConst)
),
retVal
);
LambdaExpression lambda = Expression.Lambda(block, new[] { parameter });
return lambda.Compile().DynamicInvoke(source);
}
I've used a somewhat different set of arguments here to simplify my expressions.
The code works when derivedType is, in fact, a Type derived from S. However, if it isn't -- when I'm expecting the code to return retVal = null -- it blows up at the following line:
Expression.Assign(retVal, Expression.Property(varDest, fieldName)),
complaining that fieldName is not a property of varDest. Which is correct in that case...but I was expecting the "if true" arm of the Condtional expression to not be evaluated if the test expression was false. That's clearly not the case.
What I don't know about expression trees would fill (more than) a book. But if someone can point out where I'm going off the rails I'd appreciate it.
Not sure if you ever got this answered but here's what you need
public static object OrderByDerivedProperty<TSource>(TSource source, Type derivedType, string propertyOrFieldName)
{
if (!derivedType.IsClass)
{
throw new Exception("Derived type must be a class.");
}
ParameterExpression sourceParameter = Expression.Parameter(typeof(object), "source");
ParameterExpression typeAsVariable = Expression.Variable(derivedType);
ParameterExpression returnVariable = Expression.Variable(typeof(object));
BlockExpression block = Expression.Block(
new[] { typeAsVariable,returnVariable },
Expression.Assign(
typeAsVariable,
Expression.TypeAs(
sourceParameter,
derivedType
)
),
Expression.Condition(
Expression.NotEqual(
typeAsVariable,
Expression.Constant(
null,
derivedType
)
),
Expression.Assign(
returnVariable,
Expression.Convert(
Expression.PropertyOrField(
typeAsVariable,
propertyOrFieldName
),
typeof(object)
)
),
Expression.Assign(
returnVariable,
Expression.Constant(
null,
typeof(object)
)
)
),
returnVariable
);
var lambda = Expression.Lambda<Func<object,object>>(block, new[] { sourceParameter });
return lambda.Compile().Invoke(source);
}

How can I avoid the null object reference error

I have function init, which runs on the creationComplete of the application. The init calls get_login_share_object function, in which objects are created, which are null.
Now my problem is that, I get a null object reference error on the Alert in "init()". How can I avoid that. Is it possible that I can have a check to see, if the objects are null the program should just skip reading the objects.
private function init():void
{
var stored_credentials:Object = get_login_share_object();
Alert.show(stored_credentials.check_remember +" "+ stored_credentials.alias +" "+ stored_credentials.password );
}
private function get_login_share_object():Object
{
//create or retrieve the current shared object
var so:SharedObject = SharedObject.getLocal("loginData","/");
var dataToLoad:ByteArray = so.data.ws_creds;
if(!dataToLoad)
return null;
//read in our key
var aes_key:String = ServerConfig.aes_key;
var key:ByteArray = new ByteArray();
key = Base64.decodeToByteArray(aes_key);
//read in our encryptedText
var encryptedBytes:ByteArray = new ByteArray();
dataToLoad.readBytes(encryptedBytes);
//decrypt using 256b AES encryption
var aes:ICipher = Crypto.getCipher("simple-aes128-ctr", key, Crypto.getPad("pkcs5"));
aes.decrypt(encryptedBytes);
encryptedBytes.position = 0;
var obj:Object = new Object();
obj.alias = encryptedBytes.readUTF();
obj.password = encryptedBytes.readUTF();
obj.check_remember = encryptedBytes.readUTF();
return obj;
}
You could check for the null like this:
var stored_credentials:Object = get_login_share_object();
if (stored_credentials)
Alert.show(stored_credentials.check_remember +" "+ stored_credentials.alias +" "+ stored_credentials.password );
else
trace('No Shared Object');
You should find out why those values are null and fix that first. Generally speaking, if you are expecting a value, it should not be null.
If it really is expected that some of those values are null then yes, you can check them first in two ways:
if(value != null) value.doSomething();
or
try{
Alert.show(stored_credentials.check_remember +" "+ stored_credentials.alias +" "+ stored_credentials.password );
}
catch(e:Error){
// do something else here if the statement under the try failed.
// most likely log the error message and see what it is
}
Your problem is here:
var dataToLoad:ByteArray = so.data.ws_creds;
if(!dataToLoad)
return null;
If there isn't any data to load, you're returning a null. So when you try and access the returned object's properties later, you'll get the null object reference error because you're referencing a null object. :)
There are a couple of easy solutions to this. You can check if the return value is null before you try to reference any properties like so:
if (stored_credentials != null) {
Alert.show(stored_credentials.check_remember +" "+ stored_credentials.alias +" "+ stored_credentials.password );
}
Or you can stop returning a null from your get_login_share_object function. What you return instead is totally up to you, just make sure it returns an object with all the properties you're referencing.

To check if an object is empty or not

I want to check in my function if a passed argument of type object is empty or not. Sometimes it is empty but still not null thus I can not rely on null condition. Is there some property like 'length'/'size' for flex objects which I can use here.
Please help.
Thanks in advance.
If you mean if an Object has no properties:
var isEmpty:Boolean = true;
for (var n in obj) { isEmpty = false; break; }
This is some serious hack but you can use:
Object.prototype.isEmpty = function():Boolean {
for(var i in this)
if(i != "isEmpty")
return false
return true
}
var p = {};
trace(p.isEmpty()); // true
var p2 = {a:1}
trace(p2.isEmpty()); // false
You can also try:
ObjectUtil.getClassInfo(obj).properties.length > 0
The good thing about it is that getClassInfo gives you much more info about the object, eg. you get the names of all the properties in the object, which might come in handy.
If object containes some 'text' but as3 doesn't recognize it as a String, convert it to string and check if it's empty.
var checkObject:String = myObject;
if(checkObject == '')
{
trace('object is empty');
}
Depends on what your object is, or rather what you expect it to have. For example if your object is supposed to contain some property called name that you are looking for, you might do
if(objSomeItem == null || objSomeItem.name == null || objSomeItem.name.length == 0)
{
trace("object is empty");
}
or if your object is actually supposed to be something else, like an array you could do
var arySomeItems = objSomeItem as Array;
if(objSomeItem == null || arySomeItems == null || arySomeItems.length == 0)
{
trace("object is empty");
}
You could also use other ways through reflection, such as ObjectUtil.getClassInfo, then enumerate through the properties to check for set values.... this class help:
import flash.utils.describeType;
import flash.utils.getDefinitionByName;
public class ReflectionUtils
{
/** Returns an Array of All Properties of the supplied object */
public static function GetVariableNames(objItem:Object):Array
{
var xmlPropsList:XMLList = describeType(objItem)..variable;
var aryVariables:Array = new Array();
if (xmlPropsList != null)
{
for (var i:int; i < xmlPropsList.length(); i++)
{
aryVariables.push(xmlPropsList[i].#name);
}
}
return aryVariables;
}
/** Returns the Strongly Typed class of the specified library item */
public static function GetClassByName($sLinkageName:String):Class
{
var tObject:Class = getDefinitionByName($sLinkageName) as Class;
return tObject;
}
/** Constructs an instance of the speicified library item */
public static function ConstructClassByName($sLinkageName:String):Object
{
var tObject:Class = GetClassByName($sLinkageName);
//trace("Found Class: " + tMCDefinition);
var objItem:* = new tObject();
return objItem;
}
public static function DumpObject(sItemName:String, objItem:Object):void
{
trace("*********** Object Dump: " + sItemName + " ***************");
for (var sKey:String in objItem)
{
trace(" " + sKey +": " + objItem[sKey]);
}
}
//}
}
Another thing to note is you can use a simple for loop to check through an objects properties, thats what this dumpobject function is doing.
You can directly check it as follow,
var obj:Object = new Object();
if(obj == null)
{
//Do something
}
I stole this from a similar question relating to JS. It requires FP 11+ or a JSON.as library.
function isEmptyObject(obj){
return JSON.stringify(obj) === '{}';
}
can use use the hasProperty method to check for length
var i:int = myObject.hasProperty("length") ? myObject.length: 0;

Resources