Given two POJO classes like these:
class UserA {
String name
String surname
Integer age
}
class UserB {
String name
String surname
String email
}
and relative instances:
usera = new UserA(name:'john', surname:'smith', age:20)
userb = new UserB(name:'mark', surname:'almond', email:'blah#gmail.com')
How can I merge "usera" and "userb" (usera <- userb) to get "usera" like this:
assert usera.name == 'mark'
assert usera.surname == 'almond'
assert usera.age == 20
assert usera.email == 'blah#gmail.com'
?
Generally I would like to add missing properties and values from other instances and overriding already existent properties' values in an object.
Add the properties from B to A using metaClass:
class UserA {
String name
String surname
Integer age
}
class UserB {
String name
String surname
String email
}
usera = new UserA(name:'john', surname:'smith', age:20)
userb = new UserB(name:'mark', surname:'almond', email:'blah#gmail.com')
userb.properties.each {
usera.metaClass[it.key] = it.value
}
assert usera.name == 'mark'
assert usera.surname == 'almond'
assert usera.age == 20
assert usera.email == 'blah#gmail.com'
Related
Current code:
mRealm.where(AdditionalData.class)
.contains("checklistParticipants.email", a#a.com, Case.INSENSITIVE)
.equalTo("checklistParticipants.type", 0)
.findAll();
which returns me result of similar to ANY record.
I want to check in nested query, only return record if and if both condition fulfilled. likewise in nested query, record email must be a#a.com and type=0
i tried below approach but ended up in same result.
mRealm.where(AdditionalData.class)
.contains("checklistParticipants.email",a#a.com, Case.INSENSITIVE)
.findAll()
.where()
.equalTo("checklistParticipants.type", 0)
.findAll();
Below screenshot shows 2 child items,
email= a#a.com & type = 1
email= x#x.com & type = 0
Realm checking for both value in either-or approach.
Also tried:
mRealm.where(AdditionalData.class)
.equalTo("checklistParticipants.email",a#a.com, Case.INSENSITIVE)
.and()
.equalTo("checklistParticipants.type", 0)
.findAll()
classpath "io.realm:realm-gradle-plugin:5.8.0"
UPDATE
class AdditionalData {
String name;
RealmList<ChecklistParticipants> checklistParticipants;
}
class ChecklistParticipants{
String email;
String type;
String field3;
}
as #EpicPandaForce said you need to use LinkingObjects
class AdditionalData {
String name;
#LinkingObjects(ChecklistParticipants.rlAdditionalData)
final RealmResults<ChecklistParticipants> linkedChecklistParticipants = null;
public RealmResults<RealmDocumentLines> getLinkedChecklistParticipants() {
return linkedChecklistParticipants ;
}
}
ChecklistParticipants
class ChecklistParticipants{
String email;
String type;
String field3;
AdditionalData rlAdditionalData;
public AdditionalData getAdditionalData() {
return rlAdditionalData;
}
public void setAdditionalData(AdditionalData additionalData) {
this.rlAdditionalData = additionalData ;
}
}
Then query
RealmResult<ChecklistParticipants> result = mRealm.where(ChecklistParticipants.class)
.contains("email", a#a.com, Case.INSENSITIVE)
.equalTo("type", 0)
.findAll();
then loop over the result and use getAdditionalData() from each item
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");
I am creating a site which is personel blog. I want to give a specific routing when I enter a new blog in admin panel. Normally when I save it matches the database id. I do not have access to static routing anyway.
I want the link parameter to be stored in the database when the blog is being entered via the routing
Default : localhost/ControlName/ActionName/id (localhost/Blog/GetBlogs/2)
bu I want that
Wanted : localhost/ControlName/ActionName/storedValue(localhost/Blog/GetBlog/bluesky)
or
localhost/storedValue(localhost/bluesky)
What you're talking about is a slug. You just have to add a property on your blog class to hold some unique string value that will compose part of the URL. For example:
[Index]
[StringLength(80)]
public string Slug { get; set; }
Then, when creating the blog, you either manually specify the value for Slug (make it a field in the form) or compose it by "slugifying" the title of the blog or something. I use the following string extensions:
public static string RemoveDiacritics(this string s)
{
s = s ?? string.Empty;
if (s.Length > 0)
{
char[] chars = new char[s.Length];
int charIndex = 0;
s = s.Normalize(NormalizationForm.FormD);
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
chars[charIndex++] = c;
}
return new string(chars, 0, charIndex).Normalize(NormalizationForm.FormC);
}
return s;
}
public static string Slugify(this string s, int maxLength = 80)
{
s = s ?? string.Empty;
//First to lower case
s = s.ToLowerInvariant().RemoveDiacritics();
//Replace spaces
s = Regex.Replace(s, #"\s", "-", RegexOptions.Compiled);
//Remove invalid chars
s = Regex.Replace(s, #"[^a-z0-9s\-_]", "", RegexOptions.Compiled);
//Trim dashes from end
s = s.Trim('-', '_');
//Replace double occurences of - or _
s = Regex.Replace(s, #"([\-_]){2,}", "$1", RegexOptions.Compiled);
while (s.Length > maxLength)
{
var pieces = s.Split('-');
pieces = pieces.Take(pieces.Count() - 1).ToArray();
s = string.Join("-", pieces);
}
return s;
}
Then, for example, you could do something like:
blog.Slug = blog.Title.Slugify();
However you create the slug, you'll then use the URL param to look up the blog by that:
public ActionResult GetBlog(string slug)
{
var blog = db.Blogs.SingleOrDefault(m => m.Slug == slug);
This is why the Slug property is decorated with [Index] above. That makes EF create an index for the column when it creates the table/adds the column. Any column you intend to query on should be indexed for performance reasons. Also, you have to define a set length for the column, as NVARCHAR(MAX) (the default column type for a string) cannot be indexed.
I have to bind the search results in the grid view based on search criteria. In my database primary store id value is like 10,12. When I select particular primary store id from the dropdown list i.e. 10, the search result corresponding to that primary store id need to be shown in the grid view.How to do that?
public static List<SearchKeyWord> GetAllKeywords(string key,
string primaryStoreId, string keywordStatus, int keywordId,
string categoryName, string subCategoryName)
{
keys = db.SearchKeyWords.Where(c => c.KeyWord.Contains(key) &&
(c.PrimaryStoreID == primaryStoreId ||
c.PrimaryStoreID.Split(',').ToList().Contains(primaryStoreId)) &&
(string.IsNullOrEmpty(categoryName) || c.StoreCategoryMapping == categoryName) &&
(string.IsNullOrEmpty(subCategoryName) || c.StoreSubCategoryMapping ==
subCategoryName)).ToList();
}
Edited!
Assumption -- search db.SearchKeyWords for all elements in which attribute PrimaryStoreID (a comma separated list) contains Key.
public static List<SearchKeyWord> GetAllKeywords(string key,
string primaryStoreId, string keywordStatus, int keywordId,
string categoryName, string subCategoryName)
{
return db.SearchKeyWords
.Where(c => c.PrimaryStoreID.Split(",".ToCharArray()).Contains(key));
}
Not clear at all what you want to do with the other parameters.
I have declared my c# application constant this way:
public class Constant
public struct profession
{
public const string STUDENT = "Student";
public const string WORKING_PROFESSIONAL = "Working Professional";
public const string OTHERS = "Others";
}
public struct gender
{
public const string MALE = "M";
public const string FEMALE = "F";
}
}
My validation function:
public static bool isWithinAllowedSelection(string strValueToCheck, object constantClass)
{
//convert object to struct
//loop thru all const in struct
//if strValueToCheck matches any of the value in struct, return true
//end of loop
//return false
}
During runtime, I will like pass in the user inputted value and the struct to check if the value exist in the struct. The struct can be profession and gender. How can I achieve it?
Example:
if(!isWithinAllowedSelection(strInput,Constant.profession)){
response.write("invalid profession");
}
if(!isWithinAllowedSelection(strInput,Constant.gender)){
response.write("invalid gender");
}
You probably want to use enums, not structs with constants.
Enums gives you a lot of possibilities, it is not so hard to use its string values to save it to the database etc.
public enum Profession
{
Student,
WorkingProfessional,
Others
}
And now:
To check existence of value in Profession by value's name:
var result = Enum.IsDefined(typeof(Profession), "Retired"));
// result == false
To get value of an enum as a string:
var result = Enum.GetName(typeof(Profession), Profession.Student));
// result == "Student"
If you really can't avoid using value names with whitespaces or other special characters, you can use DescriptionAttribute:
public enum Profession
{
Student,
[Description("Working Professional")] WorkingProfessional,
[Description("All others...")] Others
}
And now, to get description from Profession value you can use this code (implemented here as an extension method):
public static string Description(this Enum e)
{
var members = e.GetType().GetMember(e.ToString());
if (members != null && members.Length != 0)
{
var attrs = members.First()
.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length != 0)
return ((DescriptionAttribute) attrs.First()).Description;
}
return e.ToString();
}
This method fetches description defined in attribute and if there's none, returns value name. Usage:
var e = Profession.WorkingProfessional;
var result = e.Description();
// result == "Working Professional";