In my model I have public JObject GenericData { get; set; } for this property I need to create Jobject in my Controller that will pass data to this property. I have done this but now I need to sort data inside Jobject and I don't know how to do it. There is no sort function for Jobject out of box.
My code in controller looks like this.
var attributes = _context.AttributeRecords.Include(a => a.Attribute);
var queryRecords = attributes.Select(l => new
{
RecordId = l.RecordId,
ProjectId = l.ProjectId,
Attribute = l.Attribute.Description,
Value = l.Value,
InfoId = l.InfoId
}).ToList();
var recordsValues = queryRecords.Where(b => b.InfoId == i.InfoId).ToList();
var jObjectValues = new JObject();
foreach (var n in recordsValues)
{
if (n.Value.Contains(","))
{
var stringToSplit = n.Value;
var stringValues = stringToSplit.Split(',');
List<string> arr = new List<string>();
var allValues = "";
foreach (var d in stringValues)
{
var values = await _context.AttributeValues.FirstOrDefaultAsync(v => v.Key == n.Value);
arr.Add(values != null ? values.Description : d);
allValues = string.Join(",", arr);
}
jObjectValues.Add(n.Attribute, allValues);
}
else
{
var values = await _context.AttributeValues.FirstOrDefaultAsync(v => v.Key == n.Value);
jObjectValues.Add(n.Attribute, values != null ? values.Description : n.Value);
}
i.GenericData = jObjectValues;
}
You don't need to sort Jobject you can do it like this:
var queryRecords = attributes.Select(l => new
{
RecordId = l.RecordId,
ProjectId = l.ProjectId,
Attribute = l.Attribute.Description,
Value = l.Value,
InfoId = l.InfoId
}).OrderBy(o => o.Attribute).ToList();
I hope this will help you.
Related
I'm trying to build realtime chat through Realtime Database Firebase and Xamarin. However there is a problem like this, hope someone can help:
protected async void LoadChat()
{
string userid = "123456789";
var getroom = (await fc.Child("RecordsChat").OnceAsync<GetRoomChats>()).Select(x =>
new GetRoomChats
{
RoomID = x.Key
}).ToList();
List<GetRoomChats> listroomuser = new List<GetRoomChats>();
foreach (var room in getroom)
{
string str = null;
string[] strArr = null;
string roomget = room.RoomID;
str = roomget + "_";
char[] splitchar = { '_' };
strArr = str.Split(splitchar);
var getroomuser = strArr.Distinct().ToList();
foreach (var item in getroomuser)
{
if (item == userid)
{
var roomgetuser = new GetRoomChats()
{
RoomID = roomget
};
listroomuser.Add(roomgetuser);
}
}
}
if (listroomuser.Count() > 0)
{
var FirebaseClient = fc
.Child("RecordsChat")
.AsObservable<GetRoomChats>()
.Subscribe(async(dbevent) =>
{
//IteamGetRoomChats.Clear();
foreach (var room in listroomuser)
{
if (dbevent.Key == room.RoomID)
{
var lst = (await fc.Child("RecordsChat").Child(dbevent.Key).OrderByKey().LimitToLast(1).OnceAsync<MyDatabaseRecord>()).Select(x =>
new MyDatabaseRecord
{
NameUser = x.Object.NameUser,
Content = x.Object.Content,
RoomID = x.Object.RoomID,
DayCreate = x.Object.DayCreate,
AvatarUser = x.Object.AvatarUser,
sender_uid = x.Object.sender_uid,
receiver_uid = x.Object.receiver_uid,
receiver_read = x.Object.receiver_read
});
bool unread = false;
foreach (var i in lst)
{
if(i.sender_uid == userid)
{
i.Content = "You: " + i.Content;
var customerList = await apiServiceUserinfo.GetCustomersInfo(i.receiver_uid);
string nameget = customerList.NameStore;
string avatarget = customerList.AvatarStore;
i.NameUser = nameget;
i.AvatarUser = avatarget;
if (i.sender_read == true)
{
unread = false;
}
}
else
{
if (i.receiver_read == false)
{
i.BackgroundUser = "#f5f4f4";
unread = true;
}
}
var last = new GetRoomChats()
{
NameLast = i.NameUser,
ContentLast = i.Content,
RoomID = i.RoomID,
DayCreateLast = i.DayCreate,
AvatarLast = i.AvatarUser,
BackgroundUnread = i.BackgroundUser,
DotUnread = unread
};
IteamGetRoomChats.Add(last);
}
}
}
});
}
BindingContext = this;
}
In my example above, it actually gets the data. I try to check in the loop, to get the last content of the message. However, the displayed results are duplicated
Looking forward to everyone's help. Thank you!
In the following code only one property is updated at a time and previously updated properties are ignored. I know that syntax nodes are immutable so I'm missing something. What I end up with is that only the last replaced property is updated. What am I missing?
var newMemberDeclarations = new SyntaxList<MemberDeclarationSyntax>();
newMemberDeclarations.AddRange(#class.Members);
foreach (var prop in props)
{
var oldProperty = (PropertyDeclarationSyntax)prop;
// e.g. Customer or ICollection<Customer>
if (oldProperty.Type.Kind() == SyntaxKind.IdentifierName ||
oldProperty.Type.Kind() == SyntaxKind.GenericName)
{
var memberAttributes = new SyntaxList<AttributeListSyntax>().AddRange(oldProperty.AttributeLists).Add(jsonIgnoreAttribute);
var newProperty = SyntaxFactory.PropertyDeclaration(
memberAttributes,
oldProperty.Modifiers,
oldProperty.Type,
oldProperty.ExplicitInterfaceSpecifier,
oldProperty.Identifier,
oldProperty.AccessorList
);
var replaced = #class.Members.Replace(oldProperty, newProperty);
// This ignores previously updated property
// and only adds the attribute on the last replaced property
newMemberDeclarations.AddRange(replaced);
}
}
var attributes = #class.AttributeLists.AddRange(attributeLists);
root = root.ReplaceNode(#class, #class.WithAttributeLists(attributes))
.AddUsings(usingSerialization, usingCollections, usingJson)
.WithMembers(newMemberDeclarations)
.NormalizeWhitespace();
foreach (var classDeclaration in classDeclarations)
{
var #class = classDeclaration as ClassDeclarationSyntax;
List<AttributeListSyntax> attributeLists = new List<AttributeListSyntax>();
attributeLists.Add(serializableAttribute);
var guidTypeSyntax = SyntaxFactory.ParseTypeName(typeof(Guid).FullName) as QualifiedNameSyntax;
var dateTimeTypeSyntax = SyntaxFactory.ParseTypeName(typeof(DateTime).FullName) as QualifiedNameSyntax;
var customTypes = #class.DescendantNodes().Where(x => x is PropertyDeclarationSyntax)
.Select(x => (PropertyDeclarationSyntax)x)
.Where(x => x.Type.Kind() == SyntaxKind.IdentifierName || x.Type.Kind() == SyntaxKind.GenericName)
;
customTypes.ToList().ForEach(t => // .Type.GetType().FullName
{
bool isGuid = ((IdentifierNameSyntax)t.Type).Identifier.Value == guidTypeSyntax.Right.Identifier.Value;
bool isDateTime = ((IdentifierNameSyntax)t.Type).Identifier.Value == dateTimeTypeSyntax.Right.Identifier.Value;
if (t.Type is GenericNameSyntax)
{
var args = ((GenericNameSyntax)t.Type).TypeArgumentList.Arguments;
foreach(var arg in args)
{
if(arg is IdentifierNameSyntax)
{
if (!(isGuid || isDateTime))
{
var type = ((IdentifierNameSyntax)arg).Identifier.Value.ToString();
var attribute = CreateKnownTypeAttribute(type);
var knownTypeEntityHashSetAttribute = CreateKnownTypeAttribute($"HashSet<{type}>");
attributeLists.Add(knownTypeEntityHashSetAttribute);
attributeLists.Add(attribute);
}
}
}
}
else if(t.Type is IdentifierNameSyntax)
{
if (!(isGuid || isDateTime))
{
var identifier = ((IdentifierNameSyntax)t.Type).Identifier.Value.ToString();
var attribute = CreateKnownTypeAttribute(identifier);
var knownTypeEntityHashSetAttribute = CreateKnownTypeAttribute($"HashSet<{identifier}>");
attributeLists.Add(knownTypeEntityHashSetAttribute);
attributeLists.Add(attribute);
}
}
});
var members = new SyntaxList<MemberDeclarationSyntax>(#class.Members);
customTypes.ToList().ForEach(oldProperty =>
{
var memberAttributes = new SyntaxList<AttributeListSyntax>().AddRange(oldProperty.AttributeLists).Add(jsonIgnoreAttribute);
var newProperty = SyntaxFactory.PropertyDeclaration(
memberAttributes,
oldProperty.Modifiers,
oldProperty.Type,
oldProperty.ExplicitInterfaceSpecifier,
oldProperty.Identifier,
oldProperty.AccessorList
) as MemberDeclarationSyntax;
if (oldProperty.Type is IdentifierNameSyntax)
{
bool isGuid = ((IdentifierNameSyntax)oldProperty.Type).Identifier.Value == guidTypeSyntax.Right.Identifier.Value;
bool isDateTime = ((IdentifierNameSyntax)oldProperty.Type).Identifier.Value == dateTimeTypeSyntax.Right.Identifier.Value;
bool isInt = oldProperty.Type.Kind() == SyntaxKind.IntKeyword;
bool isFloat = oldProperty.Type.Kind() == SyntaxKind.FloatKeyword;
if (!(isGuid || isDateTime))
{
var identifier = oldProperty.Identifier.Value;
var indexOf = members.IndexOf(m => m is PropertyDeclarationSyntax ? ((PropertyDeclarationSyntax)m).Identifier.Value == identifier : false);
members = members.RemoveAt(indexOf).Add(newProperty);
}
}
else if(oldProperty.Type is GenericNameSyntax)
{
var identifier = oldProperty.Identifier.Value;
var indexOf = members.IndexOf(m => m is PropertyDeclarationSyntax
? ((PropertyDeclarationSyntax)m).Identifier.Value == identifier : false);
members = members.RemoveAt(indexOf).Add(newProperty);
}
});
var attributes = #class.AttributeLists.AddRange(attributeLists);
var c = SyntaxFactory.ClassDeclaration(#class.Identifier)
.WithBaseList(#class.BaseList)
.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword),
SyntaxFactory.Token(SyntaxKind.PartialKeyword))
.WithAttributeLists(attributes)
.AddMembers(members.ToArray());
root = root.ReplaceNode(#class, c)
.AddUsings(usingSerialization, usingCollections, usingSerialisation)
.NormalizeWhitespace();
}
I want to retrieve data from Project.Models.transaction_details by using linq, comparing value from list of string (List).
here is my code
List<transaction_details> transactions = new List<transaction_details>();
List<string> date_list = new List<string>();
// date_list output is ["2020-01-01","2020-01-02",2020-01-03",...,"2020-01-31"]
while (sdr.Read())
{
transactions.Add(new transaction_details
{
ID = sdr.GetInt32("ID"),
Transdate = sdr.GetDateTime("Transdate"),
Debit = sdr.GetDecimal("Debit"),
TransactionName =sdr.GetString("TransactionName"),
BranchID = sdr.GetString("BranchID")
});
}
var array1Index = date_list.Select((i, index) => new { Index = index, i = i }).ToList();
List<transaction_details> arrayresult = new List<transaction_details>();
var query1 = from a in array1Index
select transactions.Contains(a.i) == true ? a.i : "";
arrayresult = query1.ToList();
arrayresult.ForEach(x => {
Console.Write(x + " ");
});
My problem is (a.i) is an error.
Cannot convert 'string' to 'Project.Models.transaction_details'.
you probably mean to check the transaction date. try this:
var query1 = from a in array1Index
select transactions.Any(t => t.Transdate == a.i) == true ? a.i : "";
EDIT:
if you want a list of transactions try this:
var query1 = from t in transactions
where array1Index.Any(a => a.i == t.Transdate)
select t;
var query1 = from t in transactions
where array1Index.Any(a => a.i == t.Transdate);
try this
I was trying to get employee list which not already available in another list. but im getting only first element from array list.
ex : if i try EmployeeId = new int[2] {5, 2}; the list excluding only '5'. So please help me correct my below code.
public JsonResult GetEmployees(int[] EmployeeId)
{
var dbs = new dbContext();
if (EmployeeId != null)
{
foreach (var emp in EmployeeId)
{
var EmpList = dbs.Employees.Select(e => new
{
EmployeeId = e.EmployeeId,
Name = e.EmployeeName,
Job = e.Job.JobName,
Currency = e.Currency.CurrencyName,
Amount = e.Amount
}).Where(o => o.EmployeeId != emp);
return Json(EmpList, JsonRequestBehavior.AllowGet);
}
}
return null
}
Try this :
var employeeList = dbs.Employees.
.Where(e => EmployeeId.All(x=> x != e.EmployeeId))
.Select(e => new
{
EmployeeId = e.EmployeeId,
Name = e.EmployeeName,
Job = e.Job.JobName,
Currency = e.Currency.CurrencyName,
Amount = e.Amount
});
return Json(EmpList, JsonRequestBehavior.AllowGet);
}
Have you tried stepping through your code?
Your foreach iterates over your EmployeeId array.
Since you have a return statement in your foreach it exits the function at that point and it only uses the first element of your array.
You need something like this:
public JsonResult GetEmployees(int[] EmployeeId)
{
var dbs = new dbContext();
if (EmployeeId != null)
{
var EmpList = dbs.Employees.Where(EmployeeId.Contains(e.EmployeeId))
.Select(e => new
{
EmployeeId = e.EmployeeId,
Name = e.EmployeeName,
Job = e.Job.JobName,
Currency = e.Currency.CurrencyName,
Amount = e.Amount
}).Where(o => o.EmployeeId != emp);
return Json(EmpList, JsonRequestBehavior.AllowGet);
}
return null;
}
I am using CRM 4 and the SDK to grab cases like so:
public List<Case> GetCases()
{
List<Case> cases = new List<Case>();
#region Retrieve Resolved Cases
try
{
InitSession();
RetrieveMultipleRequest req = new RetrieveMultipleRequest();
req.ReturnDynamicEntities = true;
//QueryExpression says what entity to retrieve from, what columns we want back and what criteria we use for selection
QueryExpression qe = new QueryExpression();
qe.EntityName = EntityName.incident.ToString();
List<string> attributes = new string[] {
"incidentid","title" ,"description", "ticketnumber", "statuscode",
"kez_allocatedhours",
"customerid",
"casetypecode"
}.ToList();
//columns to retireve
ColumnSet AvailabilityColumnSet = new ColumnSet();
AvailabilityColumnSet.Attributes = attributes.ToArray();
qe.ColumnSet = AvailabilityColumnSet;
//filter
FilterExpression fe = new FilterExpression();
fe.FilterOperator = LogicalOperator.And;
//condtion for filter
ConditionExpression isResolved = new ConditionExpression();
isResolved.AttributeName = "statuscode";
isResolved.Operator = ConditionOperator.NotEqual;
isResolved.Values = new string[] { "5" };
fe.Conditions = new ConditionExpression[] { isResolved }; //Add the conditions to the filter
qe.Criteria = fe; //Tell the query what our filters are
req.Query = qe; //Tell the request the query we want to use
//retrieve entities
RetrieveMultipleResponse resp = svc.Execute(req) as RetrieveMultipleResponse;
if (resp != null)
{
BusinessEntity[] rawResults = resp.BusinessEntityCollection.BusinessEntities;
List<DynamicEntity> castedResults = rawResults.Select(r => r as DynamicEntity).ToList();
foreach (DynamicEntity result in castedResults)
{
string id = GetProperty(result, "incidentid");
string title = GetProperty(result, "title");
string description = GetProperty(result, "description");
string ticket = GetProperty(result, "ticketnumber");
string customer = GetProperty(result, "customerid");
int statuscode = -1;
string statusname = "";
double estHours = 0.0;
string casetype = "";
int casetypecode = -1;
Property prop = result.Properties.Where(p => p.Name == "statuscode").FirstOrDefault();
if (prop != null)
{
StatusProperty status = prop as StatusProperty;
if (status != null)
{
statuscode = status.Value.Value;
statusname = status.Value.name;
}
}
prop = result.Properties.Where(p => p.Name == "kez_allocatedhours").FirstOrDefault();
if (prop != null)
{
CrmFloatProperty fl = prop as CrmFloatProperty;
if (fl != null)
{
estHours = fl.Value.Value;
}
}
prop = result.Properties.Where(p => p.Name == "casetypecode").FirstOrDefault();
if (prop != null)
{
PicklistProperty fl = prop as PicklistProperty;
if (fl != null)
{
casetype = fl.Value.name;
casetypecode = fl.Value.Value;
}
}
Case c = new Case();
c.ID = id;
c.Title = title;
c.Description = description;
c.StatusCode = statuscode;
c.StatusName = statusname;
c.TicketNumber = ticket;
c.CustomerName = customer;
c.EstimatedHours = estHours;
c.Type = casetype;
c.TypeCode = casetypecode;
bool allowedThroughStat = true;
bool allowedThroughType = true;
var userStatuses = SettingsManager.Get("CRMUserStatusReasons").Split(';').ToList().Where(p => p.Length > 0).ToList();
var userTypes = SettingsManager.Get("CRMUserCaseTypes").Split(';').ToList().Where(p => p.Length > 0).ToList();
if(userStatuses.Count > 0 && !userStatuses.Contains(c.StatusCode.ToString()))
{
allowedThroughStat = false;
}
if (userTypes.Count > 0 && !userTypes.Contains(c.TypeCode.ToString()))
{
allowedThroughType = false;
}
if(allowedThroughStat && allowedThroughType)
cases.Add(c);
}
}
}// end try
catch (Exception)
{
return null;
// The variable 'e' can access the exception's information.
// return "Error Message: " + e.Message.ToString() + " | Stack Trace: " + e.StackTrace.ToString();
}
return cases;
#endregion
}
However, now I need to be able to change the status and title of a case from C# given its incidentid.
Ive looked at the SDK docs and cannot find an example of this.
Anyone work with this before?
Thanks
Simply put, above is code to read an incident. Could I get an example of writing an incident field, Just one. Ex: How could I change the title of an incident.
You can call the Update method on the CrmService. Here is the SDK article.
Case c = new Case();
c.ID = id;
c.Title = title;
svc.Update(c);
To change the state of an entity you use the setstaterequest. If you want to do it to a dynamic entity there's a description in this blog