Issue in recursive function in C# - c#

My recursive function is
private dynamic FillRecursive(List<AllAccounts> flatObjects, Guid accountID)
{
List<AllAccounts> recursiveObjects = new List<AllAccounts>();
foreach (var item in flatObjects.Where(x => x.ParentID.Equals(accountID)))
{
recursiveObjects.Add(new AllAccounts
{
AccountID = item.AccountID ,
Children = FillRecursive(flatObjects, item.AccountID)
});
}
return recursiveObjects;
}
When I send request to this function from postman it stops the running program in Visual Studio Code. Kindly help me resolve this issue. Thanks

Test if this work
private dynamic FillRecursive(List<AllAccounts> flatObjects, Guid accountID, List<AllAccounts> recursiveObjects=null)
{
if(recursiveObjects==null)
recursiveObjects = new List<AllAccounts>();
foreach (var item in flatObjects.Where(x => x.ParentID.Equals(accountID)))
{
recursiveObjects.Add(new AllAccounts
{
AccountID = item.AccountID ,
Children = FillRecursive(flatObjects, item.AccountID,recursiveObjects)
});
}
return recursiveObjects;
}

Related

How to update information in the PIN on google map xamarin iOS using API

I get data from the API and I want to update information in custom pin on google map using iOS project on xamarin.
I declare my CustomPins like that:
CustomPin pin1 = new CustomPin
{
Type = PinType.Place,
Position = new Position(41.59043006333251, 24.766286971618303),
Name = "Xamarin",
Label = "Bjala river - Smoljan",
Address = "гр. Смолян",
CodeNum = 1,
AlertLevel = 2
};
customMap.CustomPins = new List<CustomPin> {
pin1,
};
customMap.Pins.Add(pin1);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(41.567797926753485, 25.389703182725665), Distance.FromKilometers(70)));
Task.Run(async () => await APIConnection(customMap.CustomPins));
My API Connection method look like:
public async Task APIConnection(List<CustomPin> pins)
{
WaterBindingData waterData = await _restServiceData.GetWaterDataForecast(GenerateRequestUri(Constants.EndPoint), GenerateRequestUriStations(Constants.EndPoint));
//BindingContext = waterData;
foreach (var water in waterData.WaterStation.Stations)
{
int codeNum = water.CodeNum;
int level = water.AlertLevelStation;
int mapcode = water.MapCode;
foreach (var item in pins)
{
if (item.CodeNum == water.CodeNum)
{
item.AlertLevel = level;
item.CodeNum = codeNum;
item.MapCode = mapcode;
}
}
}
}
So in waterData come data from this API I want to update AlertLevel, CodeNum and MapCode in the pins with water.CodeNum;, water.AlertLevelStation; and water.MapCode; from the API.
PROBLEM: The problem is there: waterData come with data and I debugging this code and he enter in the if else statement and not Update the information in the infoBoxWindow.. how to fix this problem ?
But the data are here in waterData.WaterStations.Stations
---------UPDATE--------
I try this way:
foreach (var water in waterData.WaterStation.Stations)
{
int codeNum = water.CodeNum;
int level = water.AlertLevelStation;
int mapcode = water.MapCode;
foreach (var item in pins)
{
if (item.CodeNum == water.CodeNum)
{
item.AlertLevel = level;
item.CodeNum = codeNum;
item.MapCode = mapcode;
}
}
}
customMap.Pins.Clear();
foreach(var item in pins)
{
customMap.Pins.Add(item);
}
And I receive error in main.cs file:
Object reference not set to an instance of an object
Changing the property while retrieving the list would not update the UI in the map .
Try to clear and readd the items after the loop .
foreach (var water in waterData.WaterStation.Stations)
{
int codeNum = water.CodeNum;
int level = water.AlertLevelStation;
int mapcode = water.MapCode;
foreach (var item in pins)
{
if (item.CodeNum == water.CodeNum)
{
item.AlertLevel = level;
item.CodeNum = codeNum;
item.MapCode = mapcode;
}
}
}
customMap.Pins.Clear();
foreach(var item in pins)
{
customMap.Pins.Add(item);
}

Executing multiple requests xrm sdk [duplicate]

I am using ExecuteMultipleResponse method to insert 10 account records at a time using SSIS.
List<Entity> _Accounts = new List<Entity>();
// Check the batch size and process
public override void InputAccount_ProcessInput(InputAccountBuffer Buffer)
{
//List<int> personIDs = new List<int>();
int index = 0;
while (Buffer.NextRow())
{
_Accounts.Add(InputAccountFromBuffer(Buffer));
//personIDs.Add(int.Parse(Buffer.sPersonID));
index++;
if (index == 10)
{
ImportBatch();
index = 0;
}
}
ImportBatch();
}
private void ImportBatch()
{
if (_Accounts.Count > 0)
{
var multipleRequest = new ExecuteMultipleRequest()
{
Settings = new ExecuteMultipleSettings()
{
ContinueOnError = true,
ReturnResponses = true
},
Requests = new OrganizationRequestCollection()
};
foreach (var profContact in _Accounts)
{
CreateRequest reqCreate = new CreateRequest();
reqCreate.Target = profContact;
reqCreate.Parameters.Add("SuppressDuplicateDetection", false);
multipleRequest.Requests.Add(reqCreate);
}
ExecuteMultipleResponse multipleResponses = (ExecuteMultipleResponse)organizationservice.Execute(multipleRequest);
var responses = (ExecuteMultipleResponseItemCollection)multipleResponses.Results["Responses"];
foreach (var response in responses)
{
if (response.Fault != null)
{
// A fault has occurred, handle it here
}
else
{
// THIS IS WHERE I KNOW THE GUID VALUE EXIST.
}
}
//IEnumerator f = multipleResponses.Responses.GetEnumerator();
_Accounts.Clear();
}
}
Above code is working fine, however, I now need to read and store Guids from response to a List. This information is essential for the next step in the package. I know, if I am creating single record I can simply say,
Guid newRecord = _service.Create(account);
I even managed to get down to check if the response have 'Fault' or not and if it doesn't have fault then Guid value should exist in the response.
Running response.Response.Results.Values in QuickWatch shows me the guid but I just can't find a way to read it directly and store it as a Guid.
The guid of a created record should be stored in the OrganizationResponse which can be found inside the ExecuteMultipleResponseItem
Try the following to get the guid as a string:
string id = response.Response.Results["id"].ToString()
If it works as expected you should also be able to instantiate a guid, if needed:
Guid guid = new Guid(id);

ExecuteMultipleResponse; How to read and store Guids from the response

I am using ExecuteMultipleResponse method to insert 10 account records at a time using SSIS.
List<Entity> _Accounts = new List<Entity>();
// Check the batch size and process
public override void InputAccount_ProcessInput(InputAccountBuffer Buffer)
{
//List<int> personIDs = new List<int>();
int index = 0;
while (Buffer.NextRow())
{
_Accounts.Add(InputAccountFromBuffer(Buffer));
//personIDs.Add(int.Parse(Buffer.sPersonID));
index++;
if (index == 10)
{
ImportBatch();
index = 0;
}
}
ImportBatch();
}
private void ImportBatch()
{
if (_Accounts.Count > 0)
{
var multipleRequest = new ExecuteMultipleRequest()
{
Settings = new ExecuteMultipleSettings()
{
ContinueOnError = true,
ReturnResponses = true
},
Requests = new OrganizationRequestCollection()
};
foreach (var profContact in _Accounts)
{
CreateRequest reqCreate = new CreateRequest();
reqCreate.Target = profContact;
reqCreate.Parameters.Add("SuppressDuplicateDetection", false);
multipleRequest.Requests.Add(reqCreate);
}
ExecuteMultipleResponse multipleResponses = (ExecuteMultipleResponse)organizationservice.Execute(multipleRequest);
var responses = (ExecuteMultipleResponseItemCollection)multipleResponses.Results["Responses"];
foreach (var response in responses)
{
if (response.Fault != null)
{
// A fault has occurred, handle it here
}
else
{
// THIS IS WHERE I KNOW THE GUID VALUE EXIST.
}
}
//IEnumerator f = multipleResponses.Responses.GetEnumerator();
_Accounts.Clear();
}
}
Above code is working fine, however, I now need to read and store Guids from response to a List. This information is essential for the next step in the package. I know, if I am creating single record I can simply say,
Guid newRecord = _service.Create(account);
I even managed to get down to check if the response have 'Fault' or not and if it doesn't have fault then Guid value should exist in the response.
Running response.Response.Results.Values in QuickWatch shows me the guid but I just can't find a way to read it directly and store it as a Guid.
The guid of a created record should be stored in the OrganizationResponse which can be found inside the ExecuteMultipleResponseItem
Try the following to get the guid as a string:
string id = response.Response.Results["id"].ToString()
If it works as expected you should also be able to instantiate a guid, if needed:
Guid guid = new Guid(id);

Fetch the objectId from Parse.ParseObject

I am trying to figure out how to obtain the objectId from an query. What i am trying to accomplish is that I want to know if a object with a specific username and password exists in my class and then if yes, get the objectId and save it in my Unity game!
Here is how I am trying to do so with no luck:
void OnClick(){
PrimeAI.ShowSpinner();
LoginUsername = GameObject.Find("UsernameLogin").GetComponent<UIInput>().value;
LoginPassword = GameObject.Find("PasswordLogin").GetComponent<UIInput>().value;
var query = ParseObject.GetQuery("Players")
.WhereEqualTo("playername", LoginUsername)
.WhereEqualTo("password", Constant.Md5Sum(LoginPassword));
query.CountAsync().ContinueWith(t => {
int count = t.Result;
if(count == 1){
GetUserData(LoginUsername);
} else {
LoginError = true;
}
});
}
public void GetUserData(string UserName){
var query = ParseObject.GetQuery("Players")
.WhereEqualTo("playername", UserName);
query.FindAsync().ContinueWith(t => {
IEnumerable<ParseObject> results = t.Result;
OnlyOnce = true;
foreach (var result in results) {
print("Here: "+result["objectId"]);
}
});
}
It works fine until the foreach loop... How can I accomplish this and what am i doing wrong?
Any help is appreciated :-)
Do a Find rather than a CountAsync. Then just access the objectID from the returned object. If you are concerned about moving the whole object when you don't need it, use selectKeys to select only the attributes you want.
-Bob
foreach (var result in results) {
print("Here: "+ result.objectId);
}

Update variable in foreach

I have an issue related to updating an object by reference and not sure exactly what is going on.
I need to delete a list of rules and for logging I need to load another field
ruleItem.ReferencedItemValue = eventEntity.Title;
When
builder.LogDelete(showRule, showRuleResource.ToAuditLog(), "Logic Rule");
is called the ReferencedItemValue is not populated.
Any ideas, suggestions, alternatives?
Thanks
CODE:
public void DeleteCustomLogicRule(int[] ruleIds){
var rules = uow.Context.ShowRules.Where(sr => ruleIds.Contains(sr.Id)).ToList();
if (rules.Any())
{
var showId = rules.FirstOrDefault().ShowId;
var builder = AuditBuilder.FromShowId(showId);
rules.ForEach(showRule =>
{
var showRuleResource = ToShowRuleResource(showRule);
FillReferenceValue(showRuleResource);
builder.LogDelete(showRule, showRuleResource.ToAuditLog(), "Logic Rule");
});
uow.Context.SaveChanges();
builder.ToDatabase();
}
}
private void FillReferenceValue(ShowRuleResource showRuleResource)
{
foreach (var ruleItem in showRuleResource.ItemsPredicateAppliesTo.ToList())
{
FillRuleItem(ruleItem);
}
}
private void FillRuleItem(RuleItemResource ruleItem)
{
var eventEntity = uow.Context.Events.FirstOrDefault(e => e.Id == ruleItem.ReferencedItemId.Value);
if (eventEntity != null)
ruleItem.ReferencedItemValue = eventEntity.Title;
}
try this one:
rules.ForEach(showRule =>
{
var item = showRule;
var showRuleResource = ToShowRuleResource(item);
FillReferenceValue(showRuleResource);
builder.LogDelete(item, showRuleResource.ToAuditLog(), "Logic Rule");
});
Start to dig from this function
private void FillRuleItem(RuleItemResource ruleItem)
It seems like this exspressiion
var eventEntity = uow.Context.Events.FirstOrDefault(e => e.Id == ruleItem.ReferencedItemId.Value);
is null.

Categories

Resources