I'm write this function:
public static String QueryString(string queryStringKey)
{
if (HttpContext.Current.Request.QueryString[queryStringKey] != null)
{
if (HttpContext.Current.Request.QueryString[queryStringKey].ToString() != string.Empty)
return HttpContext.Current.Request.QueryString.GetValues(1).ToString();
}
return "NAQ";
}
And i want to get just one value from querystring parameter.
for example i send "page" to my function and url is: "sth.com/?page=1&page=2"
and function return to me: "1,2" ; but i want first value: "1", How?
GetValues returns a string[] if the key exists. An array is zero based, so you get the first element by using array[0], you are using GetValues(1) in your code, i assume that you wanted the first.
You could also use the Enumerable.First extension method:
Request.QueryString.GetValues("page").First();
Since GetValues returns not an empty array but null if the key was not present you need to check that explicitely (FirstOrDefault doesn't work):
public static String QueryString(string queryStringKey)
{
if (HttpContext.Current != null && HttpContext.Current.Request != null)
{
string[] values = HttpContext.Current.Request.QueryString.GetValues("queryStringKey");
if (values != null) return values.First();
}
return "NAQ";
}
A better approach would be -
public static String QueryString(string queryStringKey)
{
if (HttpContext.Current!=null && HttpContext.Current.Request!=null && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString[queryStringKey])
{
return HttpContext.Current.Request.QueryString.GetValues(queryStringKey).First();
}
return "NAQ";
}
Related
I am studying Ceylon and have question about it metamodel. I want to create some create some base class 'DataContainer' which allow to instantiate immutable classes with build-in equals-hash implementation:
e.g. Identifier(125, "ab") == Identifier(125, "ab")
So base class should collect all shared non-variable values and use this information in 'hash' an 'equals' methods.
I have wrote this code:
shared abstract class DataContainer(ClassDeclaration declaration) {
value members = {
for (i in declaration.memberDeclarations<ValueDeclaration>())
if (!i.variable, i.name != "hash", i.name != "string") i
};
variable Integer? hashCode = null;
shared actual Boolean equals(Object that) {
if (is DataContainer that) {
for (item in members) {
value thisMember = item.memberGet(this);
value thatMember = item.memberGet(that);
if (exists thisMember, exists thatMember) {
if (thisMember != thatMember) { return false; }
} else if (thisMember exists != thatMember exists) { return false; }
}
return true;
}
return false;
}
shared actual Integer hash => hashCode else (hashCode = calculateHash());
Integer calculateHash() {
variable value result = 0;
for(i in members) {
if (exists member = i.memberGet(this)) {
result = result.xor(member.hash);
}
}
return result;
}
}
class Identifier(shared Integer? id, shared String? name) extends DataContainer(`class`) {}
The Identifier class is the client of DataContainer. I like this solution in whole but I have to pass 'class' into the super class constructor because if I use 'class' inside DataContainer it doesn't see any members of subclass.
How can I obtain actual list of extended class's members in base class methods?
Something like 'this' doesn't work...
I found solution thanks to guys from Ceylon community. The function classDeclaration(this) from ceylon.language.meta should be used instead of 'class'.
This is the final code:
shared abstract class DataContainer() {
variable Integer? _hash = null;
variable ValueDeclaration[]? _members = null;
shared actual Boolean equals(Object that) {
if (is DataContainer that) {
for (i in members) {
value thisMember = i.memberGet(this);
value thatMember = i.memberGet(that);
if (exists thisMember, exists thatMember) {
if (thisMember != thatMember) { return false; }
} else if (thisMember exists != thatMember exists) { return false; }
}
return true;
}
return false;
}
shared actual Integer hash => _hash else (_hash = calculateHash());
ValueDeclaration[] members => _members else (_members = [
for (i in classDeclaration(this).memberDeclarations<ValueDeclaration>())
if (!i.variable, i.name != "string", i.name != "hash") i
]);
Integer calculateHash() {
variable Integer result = 0;
for (i in members) {
if (exists member = i.memberGet(this)) {
result = result.xor(member.hash);
}
}
return result;
}
}
class Identifier(shared Integer? number, shared String? name) extends DataContainer() {}
Adding to Alexander's formidable answer, I took the liberty to implement a string function as well so you can just print(myObj) and it renders nicely:
shared default actual String string {
value s = StringBuilder();
s.append(type(this).declaration.name).append(" { ");
for (i in members) {
value m = i.memberGet(this);
s.append(i.name).append(":");
s.append(if(exists m) then m.string else "<null>");
}
return s.append(" }").string;
}
When I submit a HTML form with blank data it's still going into else block below:
String n=request.getParameter("uname");
String e=request.getParameter("mail");
String p=request.getParameter("pwd");
if(n==null || e==null || p==null)
{
// ...
} else
{
// ...
}
How can I make sure that it enters the if block?
Blank submitted input values do not arrive as null. Instead, they arrive as empty string. The null only means that the input value was not submitted at all (i.e. the input field was totally absent in the form).
If you're not interested in distinguishing the presence of a specific input field in the form, then add a String#isEmpty() check to the if block.
if (n == null || n.isEmpty() || e == null || e.isEmpty() || p == null || p.isEmpty()) {
// ...
}
You could even bake a custom utility method for this.
public static boolean isEmpty(String string) {
return (string == null || string.isEmpty());
}
if (isEmpty(n) || isEmpty(e) || isEmpty(p)) {
// ...
}
You can even go a refactoring step further with help of varargs.
public static boolean isOneEmpty(String... strings) {
for (String string : strings) {
if (string == null || string.isEmpty()) {
return true;
}
}
return false;
}
if (isOneEmpty(n, e, p)) {
// ...
}
If you would like to cover whitespace as well, then replace string.isEmpty() over all place by string.trim().isEmpty().
See also:
Our Servlets wiki page
How to determine which form has been submited and to validate them in a servlet
Validating numbers with Servlets and JSP
This is because uname,mail,pwd variables are not null instead these parameters contains empty strings.
i.e.
uname="";
mail="";
pwd="";
when you check whether these parameters are null or not , it results into false and your else block executes and persist the record into database.
you can create a method to check empty string(s).
public static boolean checkEmpty(String value){
if(!(value==null))
return value.isEmpty();
return true;
}
replace your if condition with this:
if(checkEmpty(n) || checkEmpty(e) || checkEmpty(p)){
}
String n=request.getParameter("uname");
if (n != null) n = n.trim();
if (n == null) n = "";
String e=request.getParameter("mail");
if(e != null) e = e.trim();
if(e == null) e = "";
String p=request.getParameter("pwd");
if(p != null) p = p.trim();
if(p == null) p = "";
//
// only process if values for all three exist
//
if((n.length() < 1) || (e.length() < 1) || (p.length() < 1))
{
// ...
} else
{
// ...
}
namespace Electronic_Filing_of_Appeals
{
public class GenerateXML
{
public ElectronicRecordAppellateCase CreateXml()
{
My lies on the CreateXML() portion of this code. The error being kicked back is
Electronic_Filing_of_Appeals.GenerateXML.CreateXml(): not all code paths return a value
I've tried different approached but the same result.
Any clue from the professionals?
Your method is suppoed to return an instance of ElectronicRecordAppellateCase class. I guess you are returning the result in some If condition in your method or so like this.
public ElectronicRecordAppellateCase CreateXml()
{
ElectronicRecordAppellateCase output=new ElectronicRecordAppellateCase();
if(someVariableAlreadyDefined>otherVariable)
{
//do something useful
return output;
}
// Not returning anything if the if condition is not true!!!!
}
Solution : Make sure you are returning a valid return value from the method.
public ElectronicRecordAppellateCase CreateXml()
{
ElectronicRecordAppellateCase output=new ElectronicRecordAppellateCase();
if(someVariableAlreadyDefined>otherVariable)
{
return output;
}
return null; //you can return the object here as needed
}
If you specify output type, your method HAS to provide a value following every path of the code. When you see this error, it means one or more scenarios in your method don't return a value of a specified type, but result in a termination of the method instead.
This is an example of such problematic method:
public ElectronicRecordAppellateCase CreateXml()
{
if (something)
{
return new ElectronicRecordAppellateCase();
}
// if the something is false, the method doesn't provide any output value!!!
}
This could be solved like this for instance:
public ElectronicRecordAppellateCase CreateXml()
{
if (something)
{
return new ElectronicRecordAppellateCase();
}
else return null; // "else" isn't really needed here
}
See the pattern?
not all code paths return value means, you function may not return a expected value
you don't show your code so I made a example
for example, the follow function has 3 paths, if parm equal 1, if parm equal 2 but if parm is not equal 1 or 2 don't return a value
function SomeObject foo(integer parm){
if (parm == 1) {
return new SomeObject();
}
if (parm == 2) {
return new SomeObject();
}
//What if parm equal something else???
}
Is there any different between stringvariable != NullValue.String and !string.IsNullOrEmpty(stringvariable) in asp.net ? then which is best ?
The first tests that the string isn't "".
As strings can be null (because they are actually references) this test could fail.
By using IsNullOrEmpty you are wrapping:
if (string != null && string.Length > 0)
in one test.
IsNullOrEmpty is implemented like:
public static bool IsNullOrEmpty(string value)
{
if (value != null)
{
return (value.Length == 0);
}
return true;
}
So it checks both an empty string, and a null string. (Where is NullValue.String defined, I cannot seem to find a reference to it in any docs, but I assume it's eiter String.Empty or "null", so your first check only checks for one of these conditions.)
.Net4 has a new function called IsNullOrWhiteSpace(string value) which also returns true if the string contains only white space.
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;