How to deal with Firestore returning null values in Map - firebase

I'm making an app using Flutter/Dart and have run into an annoying issue.
When I want to add another variable to an object, such as the FoodItem object in this example, and I need to parse the snapshot data into the dart object, the map Firestore returns usually doesn't contain the new value and ends up telling the new object to just make the new variable null.
This causes problems throughout the app. How should I approach this without null checking for every single element being parsed? Thanks!
class FoodItem with ChangeNotifier {
String name;
String barcode;
String servingSize;
String calories;
String totalFat;
String satFat;
String transFat;
String cholesterol;
String sodium;
String totalCarbs;
String protein;
String fiber;
String sugar;
bool new_variable_that_ends_up_null = false;
...
FoodItem.fromSnapshotData(Map<String, dynamic> data)
: name = data['Name'],
calories = data['Calories'],
barcode = data['Barcode'],
servingSize = data['Serving Size'],
totalFat = data['Total Fat'],
satFat = data['Saturated Fat'],
transFat = data['Trans Fat'],
cholesterol = data['Cholesterol'],
sodium = data['Sodium'],
totalCarbs = data['Total Carbs'],
fiber = data['Fiber'],
sugar = data['Sugar'],
protein = data['Protein'],
new_variable_that_ends_up_null = data['New Variable']; // This will return null when it's not already in firstore.
}

try this out :
new_variable_that_ends_up_null = data['New Variable'] ?? false
problem here is u cannot assign null to the bool it will give u error

Related

im using java. Here expected outcome should be Test.Testing, but it is returning all the data in the list. Any other way to replace *

List<String> list = new ArrayList<String>();
list.add("Test.Testing");
list.add("Test");
list.add("Testing");
String queryString = "*.*";
queryString = queryString.replaceAll("\\*" , ".*");
for (String str : list) {
if (str.matches(queryString))
System.out.println(str);
}
here expected answer should be
Test.Testing
but it is returning all the data in the list.

How to fetch local attribute value through QuerySpec in Windchill

I created a local string type attribute on a type in Windchill. I'm trying to fetch the value of that attribute using QuerySpec but it's throwing the following exception:
2019-04-16 20:53:05,092 INFO [ajp-nio-127.0.0.1-8011-exec-5]
wt.system.err - wt.query.QueryException: Attribute
"ptc_str_89typeInfoLCSProduct" is not a member of class "class
com.lcs.wc.product.LCSSKU" 2019-04-16 20:53:05,092 INFO
[ajp-nio-127.0.0.1-8011-exec-5] wt.system.err - Nested exception is:
Attribute "ptc_str_89typeInfoLCSProduct" is not a member of class
"class com.lcs.wc.produ
Following is my code:
String colorwayId = product.getFlexType().getAttribute("colorwayID")
.getColumnName();
QuerySpec qs = new QuerySpec();
int classIndex = qs.appendClassList(typeDefRef.getKey().getClass(), false);
ClassAttribute ca = new ClassAttribute(
typeDefRef.getKey().getClass(), colorwayId);
qs.appendSelect(ca, new int[] { classIndex }, false);
QueryResult qr = PersistenceHelper.manager.find(qs);
Normally ClassAttribute gets attribute name instead of column name (database column).
Your ptc_str_89typeInfoLCSProduct column is in fact typeInfoLCSProduct.ptc_str_89 like State is state.state.
To get this information, you need to use PersistableAdapter like this:
public String getAttributeColumnName(String softType, String logicalAttributeName) throws WTException {
PersistableAdapter persistableAdapter = new PersistableAdapter(softType, Locale.getDefault(), Operation.DISPLAY);
persistableAdapter.load(logicalAttributeName);
AttributeTypeSummary attributeDescriptor = persistableAdapter.getAttributeDescriptor(logicalAttributeName);
return null != attributeDescriptor ? (String) attributeDescriptor.get(AttributeTypeSummary.DESCRIPTION) : null;
}
And then use this method:
String colorwayId = getAttributeColumnName("your_softtype", "attribute_name_from_type_manager");

Replacing HashMap with TreeMap

I am trying to replace HashMap used in my code to TreeMap as I need to have the keys sorted.
But just replacing the HashMap declaration with TreeMap is running into various ClassCast exception which were not arising before. I am debugging the code but I cannot follow why is it failing? It fails in the treemap.put(key, value); statement.
private static void insertIntoIndexFile(String datatype, String value, String columnName, String tableName,
long offset) {
// TODO Auto-generated method stub
Map<Object, ArrayList<Long>> index = new TreeMap<Object, ArrayList<Long>>();
Map<Object, ArrayList<Long>> result = new TreeMap<Object, ArrayList<Long>>();
try{
String indexTableFileName = SCHEMA+"."+tableName+"."+columnName+".ndx";
File indexTableFileObject = new File(indexTableFileName);
long indexfileLength = indexTableFileObject.length();
RandomAccessFile indexTableFile = new RandomAccessFile(indexTableFileObject, "rw");
boolean isValuePresent = false;
if(indexfileLength>0){
// returns sucessfully
index = getIndexFileEntries(indexTableFileName, datatype);
// checking if the key exists
Set set1 = index.entrySet();
Iterator iterator1 = set1.iterator();
while(iterator1.hasNext()) {
Map.Entry me2 = (Map.Entry)iterator1.next();
Object key = me2.getKey();
ArrayList<Long> temp = new ArrayList<Long>();
if(key.toString().equals(value)){
System.out.println("Comparing the hashmap value to value " + key.toString());
isValuePresent = true;
temp = (ArrayList<Long>) me2.getValue();
long frequency = temp.get(0);
frequency++;
temp.set(0, frequency);
temp.add(offset);
index.put(key, temp);
break;
}
}
if(isValuePresent == false){
System.out.println("The file has values but this key was not found. Here is the updated hashmap");
ArrayList<Long> temp = new ArrayList<Long>();
temp.add(Long.parseLong("01"));
temp.add(offset);
Object key = (Object)value;
index.put(key,temp); // this line throws error
writeMapToIndexFile(tableName, columnName, datatype, index);
}else{
writeMapToIndexFile(tableName,columnName, datatype, index);
}
}catch(Exception e){
e.printStackTrace();
}
}
Here is the stacktrace :
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String
at java.lang.String.compareTo(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at Database.insertIntoIndexFile(Database.java:433)
at Database.insertIntoTable(Database.java:369)
at Database.main(Database.java:1340)
Similar stacktrace for each of short, integer etc. I expect the key to be these datatypes. Therefore I have used Object type to store the keys. But I am not trying to cast them String before inserting into the map.
Is there anything that I am overlooking while replacing a hashmap with treemap. I agree its a very broad question but any help would really be great.
Thanks for your time.

Json adds \ charcter while returning json format

I am creating an API/web service which needs to return JSON format.
I also need to create the web service as a POST request
Sample code below, see more snippets of the source code in the end of this post.
Meta meta = new Meta();
meta.recipes = new List<Recipe>();
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(meta);
return strJSON;
Problem:
When I try the response in a few REST consoles (list of consoles tried) and in the ASP.NET client, I get this format with an extra "d" and extra \ before each ". See return output below:
{"d":"{\"count\":\"0\",\"status\":\"500\",\"recipes\":[]}"}
When I try to remove serialization then I get the following format:
<Meta xmlns:xsi="w3.org/2001/XMLSchema-instance"; xmlns:xsd="w3.org/2001/XMLSchema"; xmlns="tempuri.org/">; <count>1</count> <status>200</status> <recipes> <Recipe> <recipeID>1</recipeID> <recipeName>Apple Pie</recipeName> <imageURL>service/it.jpg</imageURL> <rating/> </Recipe> </recipes> </Meta>
But I want it in the following format:
{"count":"0","status":"500","recipes":[]}
[WebMethod(Description = "Return all Recipe...")]
[ScriptMethod( ResponseFormat = ResponseFormat.Json)]
public Meta RecipeList(string ingredientId, string cuisineId, string dishTypeId, string courseId)
This still returns XML even though I return meta object and don't add serialization
Questions:
I thought the correct JSON format should be WITHOUT this "d" and the . Is this true or is the correct JSON format of the output actually WITH the "d" and the \?
If it should be without, then where do you suggest the correction should be made, on the server side or in the client side?
How should I correct this on the server side?
How can this be corrected on the client side?
[WebMethod(Description = "Return all Recipe...")]
[ScriptMethod( ResponseFormat = ResponseFormat.Json)]
public string RecipeList(string ingredientId, string cuisineId, string dishTypeId, string courseId,
string occasionId, string considerationId, string recipeType, string readyTime, string favouritebyUserId, string bookmarkbyUserId)
{
DataSet ds = new DataSet();
int rTime = 0;
if (readyTime == "") rTime = 0;
else rTime = Convert.ToInt32(readyTime);
ds = RecipeBLL.SearchRecipe(ingredientId, cuisineId, dishTypeId, courseId, occasionId, considerationId, recipeType, rTime);
// Create a multidimensional jagged array
string[][] JaggedArray = new string[ds.Tables[0].Rows.Count][];
int i = 0;
Meta meta = new Meta();
int count = 0;
meta.recipes = new List<Recipe>();
foreach (DataRow rs in ds.Tables[0].Rows)
{
Recipe recipe = new Recipe {
recipeID = rs["RecipeId"].ToString(),
recipeName = rs["RecipeTitle"].ToString(),
imageURL = rs["Photo"].ToString(),
rating = rs["Rating"].ToString()
};
meta.recipes.Add(recipe);
//mlist.Add(recipe);
count++;
}
if (count != 0)
meta.status = "200";
else
meta.status = "500";
meta.count = count.ToString();
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON1 = js.Serialize(meta);
return strJSON1;
}
It sounds like the problem is that you're returning a string from your code somewhere - and then it's being encoded as JSON by something else. So the string you're returning is:
{"count":"0","status":"500","recipes":[]}
... but whatever you're returning from thinks you're trying to return a string, rather than an object with a count etc.
You haven't shown any of your code, but I suspect the answer will be to just remove one explicit serialization call.

NameValueCollection to URL Query?

I know i can do this
var nv = HttpUtility.ParseQueryString(req.RawUrl);
But is there a way to convert this back to a url?
var newUrl = HttpUtility.Something("/page", nv);
Simply calling ToString() on the NameValueCollection will return the name value pairs in a name1=value1&name2=value2 querystring ready format. Note that NameValueCollection types don't actually support this and it's misleading to suggest this, but the behavior works here due to the internal type that's actually returned, as explained below.
Thanks to #mjwills for pointing out that the HttpUtility.ParseQueryString method actually returns an internal HttpValueCollection object rather than a regular NameValueCollection (despite the documentation specifying NameValueCollection). The HttpValueCollection automatically encodes the querystring when using ToString(), so there's no need to write a routine that loops through the collection and uses the UrlEncode method. The desired result is already returned.
With the result in hand, you can then append it to the URL and redirect:
var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
string url = Request.Url.AbsolutePath + "?" + nameValues.ToString();
Response.Redirect(url);
Currently the only way to use a HttpValueCollection is by using the ParseQueryString method shown above (other than reflection, of course). It looks like this won't change since the Connect issue requesting this class be made public has been closed with a status of "won't fix."
As an aside, you can call the Add, Set, and Remove methods on nameValues to modify any of the querystring items before appending it. If you're interested in that see my response to another question.
string q = String.Join("&",
nvc.AllKeys.Select(a => a + "=" + HttpUtility.UrlEncode(nvc[a])));
Make an extension method that uses a couple of loops. I prefer this solution because it's readable (no linq), doesn't require System.Web.HttpUtility, and it supports duplicate keys.
public static string ToQueryString(this NameValueCollection nvc)
{
if (nvc == null) return string.Empty;
StringBuilder sb = new StringBuilder();
foreach (string key in nvc.Keys)
{
if (string.IsNullOrWhiteSpace(key)) continue;
string[] values = nvc.GetValues(key);
if (values == null) continue;
foreach (string value in values)
{
sb.Append(sb.Length == 0 ? "?" : "&");
sb.AppendFormat("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(value));
}
}
return sb.ToString();
}
Example
var queryParams = new NameValueCollection()
{
{ "order_id", "0000" },
{ "item_id", "1111" },
{ "item_id", "2222" },
{ null, "skip entry with null key" },
{ "needs escaping", "special chars ? = &" },
{ "skip entry with null value", null }
};
Console.WriteLine(queryParams.ToQueryString());
Output
?order_id=0000&item_id=1111&item_id=2222&needs%20escaping=special%20chars%20%3F%20%3D%20%26
This should work without too much code:
NameValueCollection nameValues = HttpUtility.ParseQueryString(String.Empty);
nameValues.Add(Request.QueryString);
// modify nameValues if desired
var newUrl = "/page?" + nameValues;
The idea is to use HttpUtility.ParseQueryString to generate an empty collection of type HttpValueCollection. This class is a subclass of NameValueCollection that is marked as internal so that your code cannot easily create an instance of it.
The nice thing about HttpValueCollection is that the ToString method takes care of the encoding for you. By leveraging the NameValueCollection.Add(NameValueCollection) method, you can add the existing query string parameters to your newly created object without having to first convert the Request.QueryString collection into a url-encoded string, then parsing it back into a collection.
This technique can be exposed as an extension method as well:
public static string ToQueryString(this NameValueCollection nameValueCollection)
{
NameValueCollection httpValueCollection = HttpUtility.ParseQueryString(String.Empty);
httpValueCollection.Add(nameValueCollection);
return httpValueCollection.ToString();
}
Actually, you should encode the key too, not just value.
string q = String.Join("&",
nvc.AllKeys.Select(a => $"{HttpUtility.UrlEncode(a)}={HttpUtility.UrlEncode(nvc[a])}"));
Because a NameValueCollection can have multiple values for the same key, if you are concerned with the format of the querystring (since it will be returned as comma-separated values rather than "array notation") you may consider the following.
Example
var nvc = new NameValueCollection();
nvc.Add("key1", "val1");
nvc.Add("key2", "val2");
nvc.Add("empty", null);
nvc.Add("key2", "val2b");
Turn into: key1=val1&key2[]=val2&empty&key2[]=val2b rather than key1=val1&key2=val2,val2b&empty.
Code
string qs = string.Join("&",
// "loop" the keys
nvc.AllKeys.SelectMany(k => {
// "loop" the values
var values = nvc.GetValues(k);
if(values == null) return new[]{ k };
return nvc.GetValues(k).Select( (v,i) =>
// 'gracefully' handle formatting
// when there's 1 or more values
string.Format(
values.Length > 1
// pick your array format: k[i]=v or k[]=v, etc
? "{0}[]={1}"
: "{0}={1}"
, k, HttpUtility.UrlEncode(v), i)
);
})
);
or if you don't like Linq so much...
string qs = nvc.ToQueryString(); // using...
public static class UrlExtensions {
public static string ToQueryString(this NameValueCollection nvc) {
return string.Join("&", nvc.GetUrlList());
}
public static IEnumerable<string> GetUrlList(this NameValueCollection nvc) {
foreach(var k in nvc.AllKeys) {
var values = nvc.GetValues(k);
if(values == null) { yield return k; continue; }
for(int i = 0; i < values.Length; i++) {
yield return
// 'gracefully' handle formatting
// when there's 1 or more values
string.Format(
values.Length > 1
// pick your array format: k[i]=v or k[]=v, etc
? "{0}[]={1}"
: "{0}={1}"
, k, HttpUtility.UrlEncode(values[i]), i);
}
}
}
}
As has been pointed out in comments already, with the exception of this answer most of the other answers address the scenario (Request.QueryString is an HttpValueCollection, "not" a NameValueCollection) rather than the literal question.
Update: addressed null value issue from comment.
The short answer is to use .ToString() on the NameValueCollection and combine it with the original url.
However, I'd like to point out a few things:
You cant use HttpUtility.ParseQueryString on Request.RawUrl. The ParseQueryString() method is looking for a value like this: ?var=value&var2=value2.
If you want to get a NameValueCollection of the QueryString parameters just use Request.QueryString().
var nv = Request.QueryString;
To rebuild the URL just use nv.ToString().
string url = String.Format("{0}?{1}", Request.Path, nv.ToString());
If you are trying to parse a url string instead of using the Request object use Uri and the HttpUtility.ParseQueryString method.
Uri uri = new Uri("<THE URL>");
var nv = HttpUtility.ParseQueryString(uri.Query);
string url = String.Format("{0}?{1}", uri.AbsolutePath, nv.ToString());
I always use UriBuilder to convert an url with a querystring back to a valid and properly encoded url.
var url = "http://my-link.com?foo=bar";
var uriBuilder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query.Add("yep", "foo&bar");
uriBuilder.Query = query.ToString();
var result = uriBuilder.ToString();
// http://my-link.com:80/?foo=bar&yep=foo%26bar
In AspNet Core 2.0 you can use QueryHelpers AddQueryString method.
As #Atchitutchuk suggested, you can use QueryHelpers.AddQueryString in ASP.NET Core:
public string FormatParameters(NameValueCollection parameters)
{
var queryString = "";
foreach (var key in parameters.AllKeys)
{
foreach (var value in parameters.GetValues(key))
{
queryString = QueryHelpers.AddQueryString(queryString, key, value);
}
};
return queryString.TrimStart('?');
}
This did the trick for me:
public ActionResult SetLanguage(string language = "fr_FR")
{
Request.UrlReferrer.TryReadQueryAs(out RouteValueDictionary parameters);
parameters["language"] = language;
return RedirectToAction("Index", parameters);
}
You can use.
var ur = new Uri("/page",UriKind.Relative);
if this nv is of type string you can append to the uri first parameter.
Like
var ur2 = new Uri("/page?"+nv.ToString(),UriKind.Relative);

Resources