I'am using grails.
I want to set the values in map conditionally.
For Eg:
HashMap<String, String> mymap= new HashMap<String, String>();
if (author != null){
mymap['TITLE'] = book.title
}else{
mymap['TITLE'] = 'NA'
}
So, what I want to acheive is, I want to set the value of my title as "book.title" if the particular value is not null otherwise it should be a normal string "NA".
Output I'am Getting
mymap:[TITLE: NA]
Output I want
mymap:[TITLE: [TITLE1, TITLE2, NA, TITLE4, TITLE5]]
Something like this
Thanks in advance.
You are using groovy all of this can be done more elegantly:
You must be getting iteration of book from somewhere ?
Change this from:
HashMap<String, String> mymap= new HashMap<String, String>();
if (author != null){
mymap['TITLE'] = book.title
}else{
mymap['TITLE'] = 'NA'
}
to:
List titles=[]
books?.title?.each { title->
titles<< (title?:'NA')
}
def mymap=['TITLE':titles]
Use this instead :
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
List<String> myList = new ArrayList<String>();
if (author != null){
myList.add(book.title)
}else{
myList.add('NA')
}
map.put("TITLE",myList) ;
Shorter variant:
HashMap<String, List<String>> map = [:].withDefault{ [] }
map[ 'TITLE' ] << ( author ? book.title : 'NA' )
Related
My problem is in the drilldown. I want to create a drilldown on loop but all drilldown series show in one serie, the result is when I click on column, all drilldowns series show in that char.
ArrayList<Object> dataMinorAlarms = new ArrayList<>();
ArrayList<Object> dataMajorAlarms = new ArrayList<>();
ArrayList<Object> dataCriticalAlarms = new ArrayList<>();
ArrayList<Object> dataDrilldownlAlarms = new ArrayList<>();
ArrayList<Object> DrilldownlAlarms = new ArrayList<>();
for (ResumenGraph data:resumenGraphs){
HashMap<String, Object> minor = new HashMap<>();
minor.put("name", data.getName());
minor.put("y", data.getData().getMinor());
minor.put("drilldown", data.getName());
HashMap<String, Object> major = new HashMap<>();
major.put("name", data.getName());
major.put("y", data.getData().getMajor());
major.put("drilldown", data.getName());
HashMap<String, Object> critical = new HashMap<>();
critical.put("name", data.getName());
critical.put("y", data.getData().getCritical());
critical.put("drilldown", data.getName());
for (int i = 0; i < data.getDrilldown().size(); i++) {
HIColumn series4 = new HIColumn();
series4.setName(data.getName());
series4.setId(data.getName());
Object[] object2 = new Object[]{data.getDrilldown().get(i).getName(),data.getDrilldown().get(i).getData().getMajor()};
dataDrilldownlAlarms.add(object2);
DrilldownlAlarms.add(series4);
}
dataMinorAlarms.add(minor);
dataMajorAlarms.add(major);
dataCriticalAlarms.add(critical);
}
You need to use real x and y values from the Point class, there is not someting like index property.
You can find a similar example in the highcharts-android wrapper documentation.
API: https://api.highcharts.com/class-reference/Highcharts.Point#toc3
Docs: https://github.com/highcharts/highcharts-android/blob/master/README.md
Can any one please help me for this.
public Dictionary<string,object> UserExistOrNot()
{
Dictionary<string, object> result = new Dictionary<string, object>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
string _userName = "user01";
string _password = "user";
string sqlQuery = "select * from [User] t0 inner join UserProfile t1 on t0.UserId=t1.UserId where t0.UserName='" + _userName + "' and t0.Password='" + _password+"'";
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con);
DataSet ds = new DataSet();
da.Fill(ds, "usertable");
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
result.Add("UserId", dr["UserId"]);
result.Add("UserName", dr["UserName"]);
result.Add("Password", dr["Password"]);
result.Add("Email", dr["Email"]);
result.Add("Mobile", dr["Mobile"]);
result.Add("Gender", dr["Gender"]);
result.Add("Street1", dr["Street1"]);
result.Add("Street2", dr["Street2"]);
result.Add("Street3", dr["Street3"]);
result.Add("Street4", dr["Street4"]);
result.Add("CityId", dr["CityId"]);
result.Add("StateId", dr["StateId"]);
result.Add("Country", dr["Country"]);
}
}
else
return result;
return result;
}
Output displaying like this:
System.Collections.Generic.Dictionary`2[System.String,System.Object]
I want to display the data instead of type
Browser understands pure text, xml or html, but not complex types, so you have to return one of those types, or create a view with model Dictionary and iterate throw keys and vslues to see it.
How do I get the parameter / value pairs of an URL / URI using Dart? Unfortunately currently there is no built-in functionality for this problem neither in the Uri library or the Location interface.
You can use Uri.splitQueryString to split the query into a map.
There is now a queryParameters member of Uri that returns a Map
Uri u = Uri.parse("http://app.org/main?foo=bar&baz=bat");
Map<String,String> qp = u.queryParameters;
print(qp);
// {foo: bar, baz: bat}
// url=http://127.0.0.1:3030/path/Sandbox.html?paramA=1&parmB=2#myhash
void main() {
String querystring = window.location.search.replaceFirst("?", "");
List<String> list = querystring.split("&").forEach((e) => e.split("="));
print(list); // [[paramA, 1], [parmB, 2]]
}
Map<String, String> getUriParams(String uriSearch) {
if (uriSearch != '') {
final List<String> paramValuePairs = uriSearch.substring(1).split('&');
var paramMapping = new HashMap<String, String>();
paramValuePairs.forEach((e) {
if (e.contains('=')) {
final paramValue = e.split('=');
paramMapping[paramValue[0]] = paramValue[1];
} else {
paramMapping[e] = '';
}
});
return paramMapping;
}
}
// Uri: http://localhost:8080/incubator/main.html?param=value¶m1¶m2=value2¶m3
final uriSearch = window.location.search;
final paramMapping = getUriParams(uriSearch);
Say my current page url has got (http://mysite/english/faq.aspx?faqid=12123&cid=4545&intcid=65456&h=man)
string excludeQuerystring = DynConfig.Item("GoogleSEOLinkSettings/ExcludeQuerystring"); //this is the list of my exclude querystring (cid,intcid,del)
querystring = HttpContext.Current.Request.Url.AbsoluteUri.Split('?')[1]; //I will get faqid=12123&cid=4545,intcid=65456
StringBuilder fullQueryString = new StringBuilder();
if (!string.IsNullOrEmpty(excludeQuerystring) && !string.IsNullOrEmpty(querystring))
{
string[] strEQ = excludeQuerystring.Split(','); //making a array of excluded querystrings
NameValueCollection navValues = HttpUtility.ParseQueryString(querystring); //getting the list of querystring in NameValueCollection
if (navValues.Count > 0)
{
string[] strQ = navValues.AllKeys;
if(strQ.Length>0)
{
}
}
}
querystring= ?+faqid=12123&h=man //here I want updated querystring which does not have any querystring which is there in my excludeQuerystring
I am confused how to get this, actually I want to make a function which will do this all.
Please suggest!!
EDIT:
I applied new code to resolve above problem, however got little stuck while converting NameValueCollection to querystring again.
protected void Page_Load(object sender, EventArgs e)
{
string querystring = string.Empty;
string excludeList = "cid,intcid,del";
if (!string.IsNullOrEmpty(excludeList))
{
string getFinalString = GetQueryString(excludeList);
getFinalString = "?" + getFinalString;
}
}
public string GetQueryString(string excludeArray)
{
string retQueryString = string.Empty;
if (excludeArray.IndexOf(",") != -1)
{
string[] strArray = excludeArray.Split(",".ToCharArray());
NameValueCollection filtered = new NameValueCollection();
filtered.Add(HttpUtility.ParseQueryString(Request.Url.Query));
if (filtered.HasKeys())
{
foreach (string strMatch in strArray)
{
filtered.Remove(strMatch);
}
retQueryString = filtered.ToString(); //Here I am not able to convert back to querystring, however there are other ways to get it like (http://leekelleher.com/2008/06/06/how-to-convert-namevaluecollection-to-a-query-string/), is there any other way to do that
}
}
return retQueryString;
}
Below is the perfect solution I got it, any comments on this.
string excludeList = "cid,intcid,del";
string getFinalString = Regex.Replace(Regex.Replace(Regex.Replace(Request.Url.Query, #"^\?", "&"), "&(" + excludeList.Replace(",", "|") + ")=[^&]*", "", RegexOptions.IgnoreCase), "^&", "?");
We cannot delete a query string directly like below:
Request.QueryString.Remove("foo")
If you do this, you will get an error - collection is read-only. So, we need to write the below code before deleting the query string.
In C#:
PropertyInfo isreadonly =
typeof(System.Collections.Specialized.NameValueCollection).GetProperty(
"IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
// make collection editable
isreadonly.SetValue(this.Request.QueryString, false, null);
// remove
this.Request.QueryString.Remove("foo");
Hope this will help you !!
yes there is a way to compare two arrays
var array1 = new byte[] { 1, 2, 5, 4 };
var array2 = new byte[] { 1, 2, 3, 4 };
var areEqual = array1.SequenceEqual(array2); //return boolean value True or False
I want to create a method which can takes the properties I possibly may update and leaving those not interested untouched.
Here is what I did:
public static void updateTable(int id, string field1, string field2, string field3){
using(var context = new Entities()){
var obj = context.Table.Where(x=>x.id == id).FirstOrDefault();
if(obj != null){
obj.field1 = field1;
...
obj.SaveChanges();
}
}
}
But in this pattern, I need to pass all 4 parameters into the method even I just want to update only one field. Is there any generic solution to update only the fields I passed in?
I came up something like this:
public static void updateTable(int id, object data_json){
using(var context = new Entities()){
var obj = context.Table.Where(x=>x.id == id).FirstOrDefault();
if(obj != null){
if(data_json['field1']!=null) //something like this
obj.field1 = data_json['field1'];
...
obj.SaveChanges();
}
}
}
But this can't handle the case that I do want to set a field to be null. Or is there any better solution?
If you don't care about updating relationships, you can use ApplyCurrentValues, which only updates the scalar properties.
E.g:
public static void updateTable(int id, object data_json){
using(var context = new Entities()) {
var obj = context.Table.Where(x=>x.id == id).FirstOrDefault();
context.ApplyCurrentValues("Table", data_json);
}
}
It assumes an entity with the same key is already attached in the graph. In this case, the query for var obj will ensure the object is in the graph, then it's contents are overridden with the scalar properties on the supplied object.
You might need an explicit cast on data_json to ensure it is of the same type contained in the entity set.
Using an ExpandoObject would allow you to send in only the properties you want to set, and would allow you to specify null values as well.
For example:
public static void updateTable(int id, dynamic data){
using(var context = new Entities()){
var obj = context.Table.Where(x=>x.id == id).FirstOrDefault();
if(obj != null){
if (((IDictionary<string, object>)data).ContainsKey("field1"))
obj.field1 = data.field1;
...
obj.SaveChanges();
}
}
}
and you could call it like this:
dynamic data = new ExpandoObject();
data.field1 = 123;
data.field2 = null;
data.field5 = "abc";
MyClass.updateTable(1, data);
Everything can be solved with a moment of reflection. This function solves the problem:
public void UpdateTable(int id, object values)
{
using (var entities = new MyEntities())
{
var valuesType = values.GetType();
var element = entities.MyTable.Where(t => t.ID == id).First();
//We are iterating through all properties of updated element and checking
//if there is value provided for there properties in values parameter
foreach (var property in element.GetType().GetProperties())
{
var valuesProperty = valuesType.GetProperty(property.Name);
//If values contain this property
if (valuesProperty != null)
{
//taking value out of values parameter
var value = valuesProperty.GetValue(values, null);
//setting it in our element to update
property.SetValue(element, value, null);
}
}
entities.SaveChanges();
}
}
Usage:
UpdateTable(125, new { FieldA = 1, FieldB = "ABCD" });
You can even make this method more universal by adding generic table type parameter.