public int AuthenticatedUserAge(String User_name)
{
string sql = "SELECT UserName,Age FROM tblDataProg WHERE (UserName ='" + User_name + "')";
ds = GetDataSet(sql);
int help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());
return help;
}
I can't figure why this line doesn't convert the age to type int and return a value:
int help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());
Completely offtopic to the question, but I think it's worth mentioning. Please don't create your SQL statements by concatenating strings. This creates SQL Injection attack possibility. Instead consider SqlParameter class and compose your WHERE predicates using such parameters.
Here you get nice example (look especially at convenient AddWithValue method).
Thanks!
Test your assumptions more. You are assuming GetDataSet is returning a row but it possibly isn't: -
int help = 0;
if (ds.Tables[0].Rows.Count == 0)
{
throw new ApplicationException("no rows were returned, here is an error to deal with");
}
else if (ds.Tables[0].Rows[0]["Age"] == System.DbNull.Value)
{
throw new ApplicationException("a row was found but Age is null, here is an error to deal with");
}
else
{
help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());
}
try
int help;
int.TryParse(Convert.ToString(ds.Tables[0].Rows[0]["Age"]),out help);
and see the code in debug mode
When the URL is: http://www.example.com/services/product/Software.aspx , I need: "product/Software.aspx",
So far I just tried the below code :
string[] SplitUrls = Request.RawURL.Split('/');
string CategorynQuery = SplitUrls[SplitUrls.Length - 2]
+ SplitUrls[SplitUrls.Length - 1];
However, is there some other way to do this using functions IndexOf(), LastIndexOf() etc.. or any other Function? Or any possibility using Substring method ?
Please note that the above URL is just an example, there are around 100 such URls and I need the Last 2 sections for each.
Try this, using the LastIndexOf, and Substring.
string str = "http://www.example.com/services/product/Software.aspx";
int lastIndexOfBackSlash = str.LastIndexOf('/');
int secondLastIndex = lastIndexOfBackSlash > 0 ? str.LastIndexOf('/', lastIndexOfBackSlash - 1) : -1;
string result = str.Substring(secondLastIndex, str.Length - secondLastIndex);
I am also checking the presence when getting the second last index - obviously you can alter this depending on your requirements :)
You can use Uri class:
Uri uri = new Uri("http://myUrl/%2E%2E/%2E%2E");
uri.AbsoluteUri;
uri.PathAndQuery;
Not too efficient but a little more elegant:
string url = "http://www.example.com/services/product/Software.aspx";
var splitted = url.Split('/').Reverse().Take(2).Reverse().ToList();
var str = string.Format("{0}/{1}", splitted[0], splitted[1]);
Coming from a Java background: what is the recommended way to "clone" a Dart List, Map and Set?
Use of clone() in Java is tricky and questionable1,2. Effectively, clone() is a copy constructor and for that, the Dart List, Map and Set types each have a named constructor named .from() that perform a shallow copy; e.g. given these declarations
Map<String, int> numMoons, moreMoons;
numMoons = const <String,int>{ 'Mars' : 2, 'Jupiter' : 27 };
List<String> planets, morePlanets;
you can use .from() like this:
moreMoons = new Map<String,int>.from(numMoons)
..addAll({'Saturn' : 53 });
planets = new List<String>.from(numMoons.keys);
morePlanets = new List<String>.from(planets)
..add('Pluto');
Note that List.from() more generally accepts an iterator rather than just a List.
For sake of completeness, I should mention that the dart:html Node class defines a clone() method.
1 J. Bloch, "Effective Java" 2nd Ed., Item 11.
2 B. Venners, "Josh Bloch on Design: Copy Constructor versus Cloning", 2002. Referenced from here3. Quote from the article:
If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think clone is deeply broken. ---J.Bloch
3 Dart Issue #6459, clone instance(object).
With the new version of dart cloning of a Map or List become quite easy.
You can try this method for making a deep clone of List and Map.
For List
List a = ['x','y', 'z'];
List b = [...a];
For Maps
Map mapA = {"a":"b"};
Map mapB = {...mapA};
For Sets
Set setA = {1,2,3,};
Set setB = {...setA};
I hope someone find this helpful.
If you are using dart > 2.3.0, You can use spread operator something like:
List<int> a = [1,2,3];
List<int> b = [...a]; // copy of a
For lists and sets, I typically use
List<String> clone = []..addAll(originalList);
The caveat, as #kzhdev mentions, is that addAll() and from()
[Do] not really make a clone. They add a reference in the new Map/List/Set.
That's usually ok with me, but I would keep it in mind.
For deep copy (clone), you can use :
Map<String, dynamic> src = {'a': 123, 'b': 456};
Map<String, dynamic> copy = json.decode(json.encode(src));
but there may be some concerns about the performance.
This solution should work:
List list1 = [1,2,3,4];
List list2 = list1.map((element)=>element).toList();
It's for a list but should work the same for a map etc, remember to add to list if its a list at the end
Map.from() only works for 1D map.
To copy multi dimensional map without reference in dart use following method
Map<keyType, valueType> copyDeepMap( Map<keyType, valueType> map )
{
Map<keyType, valueType> newMap = {};
map.forEach
(
(key, value)
{
newMap[key] =( value is Map ) ? copyDeepMap(value) : value ;
}
);
return newMap;
}
Method-1: Recommended
For cloning a multi-dimensional (nested) List or Map, use the
json.decode() and json.encode()
List newList = json.decode(json.encode(oldList));
Map newMap = json.decode(json.encode(oldList));
Method-2:
List newList = [...oldList];
Map newMap = {...oldMap}
Method-3:
List newList = List.from(oldList);
Map newMap = Map.from(oldMap);
Method-4:
List newList = List.of(oldList);
Map newMap = Map.of(oldMap);
Method-5:
List newList = List.unmodifiable(oldList);
Map newMap = Map.unmodifiable(oldMap);
For more References:
https://www.kindacode.com/article/how-to-clone-a-list-or-map-in-dart-and-flutter/
https://coflutter.com/dart-flutter-how-to-clone-copy-a-list/
Best solution for me:
List temp = {1,2,3,4}
List platforms = json.decode(json.encode(parent.platforms));
This was my solution. I hope it can help someone.
factory Product.deepCopy(Product productToCopy) => new Product(
productToCopy.id,
productToCopy.title,
productToCopy.description,
productToCopy.price,
productToCopy.imageUrl,
productToCopy.isFavorite,
);}
To copy Map<String, List> filtered;
var filteredNewCopy = filtered.map((key, value) => MapEntry(key, [...value]));
There is no 100% bullet proof way of making an exact isolated copy, but the answer from Manish Dhruw is pretty good. However, it will only work for Maps containing simple variable types and nested Maps.
To extend it to also work with other common collections, such as List and Set, and combinations of them, you could use something like the code below.
You don't really need the DeepCopyable class, but it would be useful if you want to easily make your own classes "deep-copyable" with these functions.
abstract class DeepCopyable{
T deepCopy<T>();
}
List<T> listDeepCopy<T>(List list){
List<T> newList = List<T>();
list.forEach((value) {
newList.add(
value is Map ? mapDeepCopy(value) :
value is List ? listDeepCopy(value) :
value is Set ? setDeepCopy(value) :
value is DeepCopyable ? value.deepCopy() :
value
);
});
return newList;
}
Set<T> setDeepCopy<T>(Set s){
Set<T> newSet = Set<T>();
s.forEach((value) {
newSet.add(
value is Map ? mapDeepCopy(value) :
value is List ? listDeepCopy(value) :
value is Set ? setDeepCopy(value) :
value is DeepCopyable ? value.deepCopy() :
value
);
});
return newSet;
}
Map<K,V> mapDeepCopy<K,V>(Map<K,V> map){
Map<K,V> newMap = Map<K,V>();
map.forEach((key, value){
newMap[key] =
value is Map ? mapDeepCopy(value) :
value is List ? listDeepCopy(value) :
value is Set ? setDeepCopy(value) :
value is DeepCopyable ? value.deepCopy() :
value;
});
return newMap;
}
As I mentioned, it's obviously still not 100% bullet proof - for example you will loose type information for nested collections.
List<int> a = [1,2,3];
List<int> b = a.toList(); // copy of a
Seems to work too
**Dart 2.15
This was my solution,hope it works for you
class Person {
String? name;
int? age;
Person(this.name, this.age);
factory Person.clone(Person source) {
return Person(source.name, source.age);
}
}
final personList = [
Person('Tom', 22),
Person('Jane', 25),
];
final yourCopy = personList.map((p) => Person.clone(p)).toList();
If you are working with dynamic typed data (aka sourced from JSON or built to encode as JSON) you can use this function to perform a deep copy:
cloneDeep(value) {
if (value is List<dynamic>) {
return value.map<dynamic>(
(item) => cloneDeep(item),
).toList();
} else if (value is Map) {
return value.map<String, dynamic>(
(key, item) => MapEntry<String, dynamic>(key, cloneDeep(item)));
}
return value;
}
final list = [[],[]];
final cloned = list.copyRange(0, list.length-1);
best solution is use of toMap() and fromMap() for classes.
class A {
String title;
A(Map<String, Object> map){ // fromMap() or fromJson()
title= map['title'];
}
Map<String, Object> toMap(){
final res = <String, Object>{};
res['title'] = title;
return res;
}
}
The given answer is good, but be aware of the generate constructor which is helpful if you want to "grow" a fixed length list, e.g.:
List<String> list = new List<String>(5);
int depth = 0; // a variable to track what index we're using
...
depth++;
if (list.length <= depth) {
list = new List<String>.generate(depth * 2,
(int index) => index < depth ? list[index] : null,
growable: false);
}
I have this code,but getting some error.after that i change the code.but i wanted to know is that correct.
modifiedMessage = convertToISOfromUtf8(modifiedMessage, "ISO8859-1", "UTF-8");
char[] characters_to_removed_from_start = { ' ' };
modifiedMessage = modifiedMessage.TrimStart(characters_to_removed_from_start);
String msg_arr = modifiedMessage.Split(' ');
String keyword = msg_arr[0];
//Linq
if (keyword != null)
{
string[] key = Regex.Split(msg_arr, #keyword).Skip(0).ToArray();
// message_in = String.Join(message_in,key);
message_in = String.Join(msg_arr, key);
modifiedMessage="";
}
Those are Errors shown
Error 1 Cannot implicitly convert type 'string[]' to 'string'
Error 2 Cannot implicitly convert type 'char' to 'string'
Then i change my code like this..(Only changed code listed below)
String msg_arr = modifiedMessage.Split(' ').ToString();
String keyword = msg_arr[0].ToString();
I wanted to know my works is Correct ?
No, thats not correct, change
String msg_arr = modifiedMessage.Split(' ');
to
String[] msg_arr = modifiedMessage.Split(' ');
this will resolve "Error 1 Cannot implicitly convert type 'string[]' to 'string'"
and Error 2 dissapears also
Declare the msg_arr variable as string[] or as var.
Your syntax is not compliant to .NET and C# naming guidelines, use StyleCop to have an help.
Could someone explain why the FLEX 4.5 XMLDecoder does this to my XML-data?
var decoder:XMLDecoder = new XMLDecoder;
var $object:Object = decoder.decode( <xmltag>08.00</xmltag> );
// object = "08.00"
var decoder:XMLDecoder = new XMLDecoder;
var $object:Object = decoder.decode( <xmltag>11.00</xmltag> );
// Object = "11" (HEY! Where did my '.00' part of the string go?)
var decoder:XMLDecoder = new XMLDecoder;
var $object:Object = decoder.decode( <xmltag>11.30</xmltag> );
// Object = "11.3" (HEY! Where did my '0' part of the string go?)
The Flex deserializer also gave me issues with this. It may be interpreting them as Number objects and thus they will return short representations when toString() is called.
Try using .toFixed(2) whenever you need to print a value such as 11.00
var $object:Object = decoder.decode( <xmltag>11.00</xmltag> );
trace($object); //11
trace($object.toFixed(2)); //11.00
So, to the answer the original question of why this is happening:
In the source code for SimpleXMLDecoder (which I'm guessing has similar functionality to XMLDecoder), there's a comment in the function simpleType():
//return the value as a string, a boolean or a number.
//numbers that start with 0 are left as strings
//bForceObject removed since we'll take care of converting to a String or Number object later
numbers that start with 0 are left as strings - I guess they thought of phone numbers but not decimals.
Also, because of some hacky implicit casting, you actually have three different types -
"0.800" : String
11 : int
11.3: Number