Tree hierarchy setting flag true if child exists C# - c#

I am trying to set issetting flag to true , if child exists for a
parent.
//Class file
public class EopsModule
{
public int ID { get; set; }
public string ModuleCode { get; set; }
public string Description { get; set; }
public bool IsDefaultModule { get; set; }
public int? ParentID { get; set; }
public bool IsSetting { get; set; }
public List<EopsModule> Children { get; set; }
}
public IResponseResult GetApplicationSettingWithModule()
{
IResponseResult responseResult = new ResponseResult();
dynamic dynamic = new ExpandoObject();
try
{
var settingsDetails = _databaseManager.GetMultipleDataByJson(DatabaseStoredProcedures.spGetAllApplicationSetting.ToString()).Result;
var oObjectDeserializeObject = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(settingsDetails);
//get here all EopsModule in List<EopsModule>
var moduleTreeHierarchy = _eopsModuleManager.GetAllEopsModuleWithHierarchy().Result;
dynamic.settingsDetails = oObjectDeserializeObject;
dynamic.moduleTreeHierarchy = moduleTreeHierarchy;
string oModuleCode = string.Empty;
foreach (var item in oObjectDeserializeObject)
{
oModuleCode = item.moduleCode;
moduleTreeHierarchy.
Where(x => x.ModuleCode == oModuleCode).ToList().ForEach(x =>
{
x.IsSetting = true;
});
}
responseResult = Helper.Response.ResponseModel(dynamic, true, Helper.Constants.ApiSuccess, HttpStatusCode.OK, true);
}
catch (Exception)
{
responseResult = Helper.Response.ResponseModel(null, false, Helper.Constants.ApiFailure, HttpStatusCode.BadRequest, true);
}
return responseResult;
}
The loop i am iterating is working for parent level but , its not updating the value for child values,
wondering if it can be achieved by recursive function.
Please find the output with existing code :

Have you tried something like this? I did not pass it through compiler but you'll get the idea.
public UpdateModuleAndChildren(Module moduleTreeHierarchy) {
if(moduleTreeHierarchy.children != null && moduleTreeHierarchy.children.Count() > 0) {
moduleTreeHierarchy.children.forEach(x => { this.UpdateModuleAndChildren(x) });
module.IsSetting = true;
}
}
Let me know if it helps.
In your code you will just call this.UpdateModuleAndChildren(moduleTreeHierarchy)

Related

Looping an Array or List in C# and perform update using MongoDB

i want to loop my request and perform something for my array ( Cart ) but i dont know how to loop the request
here is the request
enter image description here
and here is the object class or the model for the request
public class OrderRRModel
{
public ObjectId id { get; set; }
public string cutomer_name { get; set; }
public string table_number { get; set; }
public List<ListCart> Cart { get; set; }
public OrderRRModel()
{
Cart = new List<ListCart>();
}
}
public class ListCart
{
public string product { get; set; }
public double amount { get; set; }
public double price { get; set; }
}
here is my full code
public ResponseModel<OrderRRModel> InsertOrderTest(string tokenAdmin, OrderRRModel entity)
{
var entityResult = new ResponseModel<OrderRRModel>();
try
{
var auth = _adminCollection.Find(x => x.token == tokenAdmin).FirstOrDefault();
if (auth != null)
{
var dates = DateTime.Now.ToUniversalTime();
// looping here
var check = _menuCollection.Find(x => x.product_name == cart.product_name).FirstOrDefault();
cart.price = check.price;
var result = _menuCollection.UpdateOne(
x => x.product_name == cart.product_name,
Builders<MenuRRModel>.Update.Set(x => x.updated_at, dates)
.Set(x => x.stock, check.stock - cart.amount) // updating stock by reducing stock based on quantity
);
// end of looping
_orderCollection.InsertOne(entity);
entityResult.Status = true;
entityResult.Messages.Add(new ResponseMessageModel()
{
Type = ResponseMessageModel.MessageType.SUCCESS,
Title = "Success",
Message = "Successful"
});
}
else
{
entityResult.Messages.Add(new ResponseMessageModel()
{
Type = ResponseMessageModel.MessageType.WARNING,
Title = "Action Failed",
Message = "Anda Tidak Memiliki Wewenang!"
});
}
}
catch (Exception ex)
{
entityResult.Messages.Add(new ResponseMessageModel()
{
Type = ResponseMessageModel.MessageType.ERROR,
Title = "Error",
Message = ex.Message
});
}
return entityResult;
}
can you guys tell me the code for looping my request ?
please be kind im a newbie
just do this
foreach (var cart in entity.cart)
{
cart.itemcart
}

Need help using Linq to transform a list into a different list

Lets say I have a list that contains 1 record:
[
{
"AccountNumber": 1234,
"eDocConfirms": true,
"eDocStatements": true,
"eDocTaxforms": false
}
]
This list is a strongly typed object with these properties:
public int AccountNumber { get; set; }
public bool? eDocConfirms { get; set; }
public bool? eDocStatements { get; set; }
public bool? eDocTaxforms { get; set; }
Using LINQ, I'd like to turn it into a list that looks like this:
[
{
"AccountNumber": 1234,
"EDocumentTypeName ": "Confirms"
},
{
"AccountNumber": 1234,
"EDocumentTypeName": "Statements"
}
]
This new list will a list of a different type:
public class DeliveryPreference
{
public int AccountNumber { get; set; }
public string EDocumentTypeName { get; set; }
}
Note that Taxforms was not included in the new list because it was set to false in the first list.
I know I could easily do this with some loops, but I would prefer using LINQ.
I understand that Stack Overflow prefers that I show what I have tried, but I am having trouble wrapping my brain around this.
For this case I would use additional function
public static IEnumerable<string> GetTrueProperties(Data t)
{
if (t.eDocConfirms == true) yield return "Confirms";
if (t.eDocStatements == true) yield return "Statements";
if (t.eDocTaxForms == true) yield return "Tax";
}
simply because it is an object and not a dictionary; else you could dynamically select properties which are true(or you could use reflection, but I think it would be too much here, since you have strongly typed object).
then it would look like
var list = new List<Data> {
new Data
{
AccountNumber = 1,
eDocConfirms = true,
eDocStatements = true,
eDocTaxForms = false
}
};
list.SelectMany(item => GetTrueProperties(item).Select(p => new DeliveryPreference
{
AccountNumber = item.AccountNumber,
EDocumentTypeName = p
}));
This is very ugly code, but it works. It should be easy to comprehend. Reflection can be extracted to a new function.
using System;
using System.Linq;
public class Program
{
public class Account {
public int AccountNumber { get; set; }
public bool? eDocConfirms { get; set; }
public bool? eDocStatements { get; set; }
public bool? eDocTaxforms { get; set; }
}
public class DeliveryPreference
{
public int AccountNumber { get; set; }
public string EDocumentTypeName { get; set; }
}
public static void Main()
{
var acc = new Account {
AccountNumber = 10,
eDocConfirms = true,
eDocStatements = false,
eDocTaxforms = true
};
var transformed = acc.GetType()
.GetProperties()
.Where(p => p.PropertyType == typeof(bool?)
&& ((bool?)p.GetValue(acc)).HasValue
&& ((bool?)p.GetValue(acc)).Value)
.Select(p => new DeliveryPreference {
AccountNumber = acc.AccountNumber,
EDocumentTypeName = p.Name.Substring(4)
});
foreach (var t in transformed) {
Console.WriteLine(t.AccountNumber);
Console.WriteLine(t.EDocumentTypeName);
}
}
}

Elastic search nest dynamic query with object initializer NEST 5.x

Hi I'm a new to elastic nest API and I'm using nest 5.x. I'm currently developing some kind of advanced search page so when user doesn't check a criteria i don't have to include that filter on my query. I'm trying to combine 2 queries under must operator with object initializer approach using nest. How to achieve it? I'm following the example on [https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/bool-queries.html]
var secondSearchResponse = client.Search(new
SearchRequest {
Query = new TermQuery { Field = Field(p => p.Name), Value = "x" } &&
new TermQuery { Field = Field(p => p.Name), Value = "y" } });
But it doesnt work cause Field class doesnt accept type arguments.
I also tried to followed this approach from this topic
[Nest Elastic - Building Dynamic Nested Query
here is my code
public HttpResponseMessage GetSearchResult([FromUri] SearchModels queries)
{
try
{
///
string result = string.Empty;
result += "queryfields + " + queries.queryfields == null ? string.Empty : queries.queryfields;
result += "datefrom + " + queries.datefrom == null ? string.Empty : queries.datefrom;
result += "dateto + " + queries.dateto == null ? string.Empty : queries.dateto;
result += "emitentype + " + queries.emitentype == null ? string.Empty : queries.emitentype;
QueryContainer andQuery = null;
//List<QueryContainer> QueryContainers = new List<QueryContainer>();
IDXNetAnnouncement record = new IDXNetAnnouncement
{
kode_emiten = queries.kodeemiten
};
#region keyword
if (!string.IsNullOrEmpty(queries.queryfields))
{
var val = queries.queryfields;
TermQuery tq = new TermQuery
{
Field = queries.queryfields,
Value = val
};
if (andQuery == null)
andQuery = tq;
else
andQuery &= tq;
//QueryContainers.Add(tq);
}
#endregion keyword
#region kodeemiten
if (!string.IsNullOrEmpty(queries.kodeemiten))
{
var val = queries.kodeemiten;
TermQuery tq = new TermQuery
{
Name = "kode_emiten",
Field = record.kode_emiten,
Value = val
};
if (andQuery == null)
andQuery = tq;
else
andQuery &= tq;
//QueryContainers.Add(tq);
}
#endregion
#region date
if (!string.IsNullOrEmpty(queries.datefrom) && !string.IsNullOrEmpty(queries.dateto))
{
DateRangeQuery dq = new DateRangeQuery();
dq.Name = "tglpengumuman";
dq.LessThanOrEqualTo = DateMath.Anchored(queries.dateto);
dq.GreaterThanOrEqualTo = DateMath.Anchored(queries.datefrom);
dq.Format = "dd/mm/yyyy";
if (andQuery == null)
andQuery = dq;
else
andQuery &= dq;
//QueryContainers.Add(dq);
}
#endregion keyword
var reqs = (ISearchResponse<IDXNetAnnouncement>)null;
if (andQuery != null)
{
reqs = conn.client.Search<IDXNetAnnouncement>(s => s
.AllIndices()
.AllTypes()
.From(queries.indexfrom)
.Size(queries.pagesize)
.Query(q => q.Bool(qb => qb.Must(m => m.MatchAll() && andQuery))));
//var json = conn.client.Serializer.SerializeToString(reqs.ApiCall.ResponseBodyInBytes);
}
else
{
reqs = conn.client.Search<IDXNetAnnouncement>(s => s
.AllIndices()
.AllTypes()
.From(queries.indexfrom)
.Size(queries.pagesize)
.Query(m => m.MatchAll()));
}
//var reqstring = Encoding.UTF8.GetString(conn.client.);
var reslts = this.conn.client.Serializer.SerializeToString(reqs,SerializationFormatting.Indented);
var resp = new HttpResponseMessage()
{
Content = new StringContent(reslts)
};
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return resp;
}
catch (Exception e)
{
var resp = new HttpResponseMessage()
{
Content = new StringContent(e.ToString())
};
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return resp;
}
}
But that returns zero result. How to achieve this? Thx anyway.
EDIT :
This is the params variabel definition. Its apoco model of search keywords
public class SearchModels
{
public string queryfields { get; set; }
public string datefrom { get; set; }
public string dateto { get; set; }
public string emitentype { get; set; }
public string kodeemiten { get; set; }
public string issuercode { get; set; }
public int indexfrom { get; set; }
public int pagesize { get; set; }
}
IDXNetAnnouncement is a poco model of search result. Its actualy a document type which is stored on the elastic server
public class IDXNetAnnouncement
{
public string perihalpengumuman { get; set; }
public string attachments { get; set; }
public string createddate { get; set; }
public bool efekemiten_spei { get; set; }
public string jmsxgroupid { get; set; }
public string tglpengumuman { get; set; }
public object errordescription { get; set; }
public string ESversion { get; set; }
public int oldfinalid { get; set; }
public bool efekemiten_etf { get; set; }
public object errorcode { get; set; }
public string jenisemiten { get; set; }
public int pkid { get; set; }
public string judulpengumuman { get; set; }
public string form_id { get; set; }
public bool efekemiten_eba { get; set; }
public string jenispengumuman { get; set; }
public string nopengumuman { get; set; }
public string kode_emiten { get; set; }
public string divisi { get; set; }
public string EStimestamp { get; set; }
public bool efekemiten_obligasi { get; set; }
public long finalid { get; set; }
public bool efekemiten_saham { get; set; }
public string kodedivisi { get; set; }
public string SearchTerms
{
get
{
return string.Format("{0} {1} {2}", judulpengumuman, kode_emiten, nopengumuman);
}
}
}
But it doesnt work cause Field class doesnt accept type arguments.
You need to ensure that you include a using static directive for Nest.Infer i.e.
using static Nest.Infer;
with the rest of the using directives.
.Query(q => q.Bool(qb => qb.Must(m => m.MatchAll() && andQuery))));
No need to wrap in a Must(), just do
.Query(q => q.MatchAll() && andQuery)
which will wrap both queries in a bool query must clause. You also don't need to null check andQuery because NEST is smart enough to not combine the two queries if either or both are null.
if (!string.IsNullOrEmpty(queries.queryfields))
{
var val = queries.queryfields;
TermQuery tq = new TermQuery
{
Field = queries.queryfields,
Value = val
};
if (andQuery == null)
andQuery = tq;
else
andQuery &= tq;
//QueryContainers.Add(tq);
}
NEST has the concept of conditionless queries so you don't need to check it queries.queryfields is null or empty, simply build the query and add it to andQuery. So it would become
var val = queries.queryfields;
andQuery &= new TermQuery
{
Field = queries.queryfields,
Value = val
};
Aside
All of the NEST documentation is generated from source code; you can trace back to the original source file by clicking on any edit link within the documentation. This will take you to a github page, such as this one for bool queries. From here, the document contains an important note that links back to the original source.

Entity Framework - Accessing Model classes that have foreign/navigation key to themselves

I have the following Model, which can be a child of the same type, and/or have many children of the same type.
public class SystemGroupModel
{
public int Id { get; set; }
public int? ParentSystemGroupModelId { get; set; }
[ForeignKey("ParentSystemGroupModelId")]
public virtual SystemGroupModel ParentSystemGroupModel { get; set; }
[InverseProperty("ParentSystemGroupModel")]
public virtual ICollection<SystemGroupModel> SubSystemGroupModels { get; set; }
}
How can I get a specific SystemGroupModel by Id that is at an unknown depth, and include all of it's children, grandchildren, great-grandchildren, etc.?
This appears to be working, which means it will build a list of any given parent, as well as children at an unlimited depth of grandchildren, great-grandchildren, and so on.
Is this the right approach?
First I created this new class
public class SystemGroupWorkingClass
{
public SystemGroupModel SystemGroupModel { get; set; }
public bool WasChecked { get; set; }
}
Then I added this code
EDIT: Updated to include the loop that builds List<SystemGroupWorkingClass>
List<SystemGroupWorkingClass> tempListSystemGroups = new List<SystemGroupWorkingClass>();
//Get the SystemGroups that were selected in the View via checkbox
foreach (var systemGroupVM in viewModel.SystemGroups)
{
if (systemGroupVM.Selected == true)
{
SystemGroupModel systemGroupModel = await db.SystemGroupModels.FindAsync(systemGroupVM.Id);
SystemGroupWorkingClass systemGroupWorkingClass = new SystemGroupWorkingClass();
systemGroupWorkingClass.SystemGroupModel = systemGroupModel;
systemGroupWorkingClass.WasChecked = false;
systemGroupWorkingClass.Selected = true;
//Make sure tempListSystemGroups does not already have this systemGroupWorkingClass object
var alreadyAddedCheck = tempListSystemGroups
.FirstOrDefault(s => s.SystemGroupModel.Id == systemGroupVM.Id);
if (alreadyAddedCheck == null)
{
tempListSystemGroups.Add(systemGroupWorkingClass);
}
}
}
for (int i = 0; i < tempListSystemGroups.Count; i++)
{
if (tempListSystemGroups[i].WasChecked == false)
{
SystemGroupModel systemGroupModel2 = await db.SystemGroupModels.FindAsync(tempListSystemGroups[i].SystemGroupModel.Id);
//Get the children, if there are any, for the current parent
var subSystemGroupModels = systemGroupModel2.SubSystemGroupModels
.ToList();
//Loop through the children and add to tempListSystemGroups
//The children are added to tempListSystemGroups as it is being iterated over
foreach (var subSystemGroupModel in subSystemGroupModels)
{
SystemGroupModel newSystemGroupModel = await db.SystemGroupModels.FindAsync(subSystemGroupModel.Id);
SystemGroupWorkingClass subSystemGroupWorkingClass = new SystemGroupWorkingClass();
subSystemGroupWorkingClass.SystemGroupModel = newSystemGroupModel;
subSystemGroupWorkingClass.WasChecked = false;
tempListSystemGroups.Add(subSystemGroupWorkingClass);
}
}
//Mark the parent as having been checked for children
tempListSystemGroups[i].WasChecked = true;
}

How do I create and insert one-to-many object with entity framework c#

I'm trying to create an object and insert to the database but keep getting the same error no matter what I try.
The row that I get the error on is ColumnGroupTest.ValidValues.Add(memberComment1); the error is
error message
NullReferenceException was unhandled by user code
my models
public class StoreColumnName
{
public int Id { get; set; }
public string StoreColumnGroupName { get; set; }
public string ColumnName { get; set; }
public string ColumnType { get; set; }
public List<StoreValidValue> ValidValues { get; set; }
}
public class StoreValidValue
{
public int Id { get; set; }
public string ValidValue { get; set; }
public StoreColumnName StoreColumnName { get; set; }
}
my controller
public ActionResult Index()
{
XDocument document = XDocument.Load(#"C:\Users\Physical.xml");
var result = document.Descendants("ColumnGroup");
foreach(var item in result){
var ColumnGroupName = item.Attribute("name").Value;
var Columns = item.Descendants("Column");
foreach (var itemColumn in Columns)
{
StoreColumnName ColumnGroup = new StoreColumnName();
var ColumnGroupTest = new StoreColumnName
{
StoreColumnGroupName = ColumnGroupName,
ColumnName = itemColumn.Attribute("name").Value,
ColumnType = itemColumn.Attribute("type").Value,
Id = 11
};
var ValidValues = itemColumn.Descendants("ValidValues");
var Values = ValidValues.Descendants("Value");
foreach (var Value in Values)
{
var memberComment1 = new StoreValidValue
{
StoreColumnName = ColumnGroupTest,
ValidValue = Value.Value,
Id = 101
};
ColumnGroupTest.ValidValues.Add(memberComment1);
}
}
}
return View();
}
(I gladly take tips on what I can improve when asking for help/guiding here).
Can anyone help ?
The issue that you're having is that you don't initialize your ValidValues property to a list. By default, those types of properties initialize to null unless you specify differently.
The best approach is to add that initialization to your constructor of that object.
public StoreColumnName() {
this.ValidValues = new List<StoreValidValue>();
}

Categories