Why is Visual Studio Debugger automatically closing when running the swagger? - c#

I am facing an stranger issue when I try to debug one of my api via Swagger. If I remove the debugger points, the swagger automatically closes without showing the output. However, if I add debugger points, the debugger stops working and a pop-up is displayed showing the message the target process exited with code 1073741819 while evaluating a function.
Here is the pop-up that I have mentioned:
Here is the api that I am getting this issue on:
[HttpGet("feerate")]
public async Task<ActionResult<ResponseVM>> GetFeeRate(FeeName feeName, FeeSchedule feeSchedule, FeeUnit feeUnit, int vcu)
{
try
{
var rv = await service.GetFeeRate(feeName, feeSchedule, feeUnit, vcu);
return Ok(new ResponseVM
{
success = true,
data = rv,
message = "Fee rate fetched successfully"
});
}
catch (Exception ex)
{
return Ok(new ResponseVM
{
success = false,
message = ex.Message
});
}
}
Here is the service function:
public async Task<PaginatedResponseVM<FeeScheduleDto>> GetFeeRate(FeeName feeName, FeeSchedule feeSchedule, FeeUnit feeUnit, int vcu)
{
var accQueryList = _dbContext.FeeSchedule.Where(x => x.FeeSchedule == feeSchedule);
accQueryList = accQueryList.Where(x => x.FeeName == feeName);
accQueryList = accQueryList.Where(x => x.FeeUnit == feeUnit);
accQueryList = accQueryList.Where(x => x.TierStart <= vcu);
accQueryList = accQueryList.Where(x => x.TierEnd > vcu);
var count = await accQueryList.CountAsync();
var items = _mapper.Map<List<FeeScheduleDto>>(await accQueryList.ToListAsync());
var returnView = new PaginatedResponseVM<FeeScheduleDto>(count, items);
return returnView;
}
Here is what I tried to resolve it:
Restarted my PC
Upgraded Visual Studio version
Repaired the Visual Studio via Control Panel
Cleaned the solution and Rebuild it
But the issue persists, so is there anyone who faced a similar issue and how it was resolved?
Any help would be appreciated.

Everyone thank you for all your replies and insights. However, the problem was with my Enum that I had used in the Dto file in the wrong manner. As the pop-up error says, I had to check again and again and at last correct my silly mistake.
So, while the enum is converted to string, the enum variable should be converted to string rather than the returning string variable itself.
Here is the correct way:
public FeeScheduleEnum FeeSchedule { get; set; }
public string FeeScheduleName { get { return FeeSchedule.ToString(); } }
So, this is where I had done that silly mistake:
public FeeScheduleEnum FeeSchedule { get; set; }
public string FeeScheduleName { get { return FeeScheduleName.ToString(); } }
Posting my answer here for anyone else doing that same mistake as I did.

Related

How to download data from Firebase?

I'm attempting to retrieve some data from a Firebase database. I've been able to do it fine in the past, but there's something wrong with my GetValueAsync() code below. When debugging it gets stuck at the "await reference.Database" line, but I'm not sure what I'm doing wrong. When running without debugging, none of the information is ever retrieved.
I'm uncertain if the problem is with the path, or the await/async function. Debugging shows that loggedUserId is storing the value before referencing it in the next line, but the rest of the function never completes or faults. The application compiles but I'm never able to capture any info from the snapshot.
The format of my database is "users" -> 78cVqzA8qNTNigsao3VvdnM0Qol2 (Which is correct) -> (several data pairs such as level : 1, lives : 3, etc)
public static async void GetUserData()
{
FirebaseApp app = FirebaseApp.DefaultInstance;
app.SetEditorDatabaseUrl("https://narwhaltrivia.firebaseio.com/");
if (app.Options.DatabaseUrl != null) app.SetEditorDatabaseUrl(app.Options.DatabaseUrl);
DatabaseReference reference = Firebase.Database.FirebaseDatabase.DefaultInstance.RootReference;
loggedUserId = FirebaseAuth.DefaultInstance.CurrentUser.UserId;
await reference.Database.GetReference("users").Child(loggedUserId).GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
Debug.LogError("Error retrieving user data");
return;
}
if (task.IsCompleted)
{
DataSnapshot userSnapshot = task.Result;
loggedEmail = userSnapshot.Child("email").GetRawJsonValue();
loggedCurrentScore = userSnapshot.Child("currentScore").GetRawJsonValue();
loggedLevel = userSnapshot.Child("level").GetRawJsonValue();
loggedLives = userSnapshot.Child("lives").GetRawJsonValue();
loggedRound = userSnapshot.Child("round").GetRawJsonValue();
loggedTotalScore = userSnapshot.Child("totalScore").GetRawJsonValue();
return;
}
});
}

How to prevent original prompt from showing on re-validation in a FormFlow?

BuildForm Method
public static IForm<FAQConversation> BuildForm()
{
return new FormBuilder<FAQConversation>()
.Field(new FieldReflector<FAQConversation>(nameof(Inquiry))
.SetValidate(AnswerInquiry)
.SetPrompt(new PromptAttribute("Okay, tell me what is your question. Enter \"back\" to go back to Products Selection."))
)
.Build();
}
Validation Method
private static async Task<ValidateResult> AnswerInquiry(FAQConversation state, object value)
{
var result = new ValidateResult();
//somecode here
if(testCase == false)
{
result.isValid = false;
result.Feedback = "Try again";
}
else
{
result.isValid = true;
}
return result;
}
My validation method returns the feedback "Try Again" text when the input on my validating field is invalid. However, it is returning both Original Prompt and the Feedback text.
Question
How do I remove the original prompt on revalidation of a field?
While FormFlow does offer a lot of customizability, the main idea behind it is to automate everything for you, which tends to indicate that at least some things are built in pretty strongly.
I understand that what you want to do is disable the prompt for a field upon "retry," which is to say that if the user was already shown the prompt for a field and they entered something invalid then they shouldn't be shown the prompt again. I can see in the source code that FormFlow doesn't really provide a special case for "retries" and the behavior of prompting when a field remains unknown is one of those built-in things. However, there is still something you can do.
FormFlow offers a (largely undocumented) way to replace what's called the "prompter." You can do this using the Prompter() method, which takes a PromptAsyncDelegate. As a starting point for your new prompter, you can find the default prompter in the FormBuilder source code:
_form._prompter = async (context, prompt, state, field) =>
{
var preamble = context.MakeMessage();
var promptMessage = context.MakeMessage();
if (prompt.GenerateMessages(preamble, promptMessage))
{
await context.PostAsync(preamble);
}
await context.PostAsync(promptMessage);
return prompt;
};
Whereas the default prompter always posts promptMessage, your replacement can surround that line with an if statement. That leaves the question of what your condition should be. We've established that FormFlow doesn't include any concept of a retry, so you'd have to build that in yourself somehow. You could include a Boolean field as a switch in FAQConversation's state, or you could even use PrivateConversationData since the prompter gives you access to the DialogContext. You might think that would be a simple matter of turning off the switch when the prompt gets displayed once or when AnswerInquiryAsync determines that the user input is invalid, but then when would the switch get turned back on? What if the user enters "back" and you want the prompt to be displayed again?
While you might find some way to more accurately represent the logic of "disabling the prompt on retry," the simplest solution I came up with was to keep track of the last message FormFlow produced and then skip the first message that comes after "Try again." It looks like this:
[Serializable]
public class FAQConversation
{
public string Inquiry { get; set; }
private string LastMessage { get; set; }
private const string TRY_AGAIN = "Try again";
public static IForm<FAQConversation> BuildForm()
{
return new FormBuilder<FAQConversation>()
// This is an alternative way of using the Field() method but it works the same.
.Field(nameof(Inquiry),
"Okay, tell me what is your question. Enter \"back\" to go back to Products Selection.",
validate: AnswerInquiryAsync)
.Prompter(PromptAsync)
.Build();
}
private static async Task<ValidateResult> AnswerInquiryAsync(FAQConversation state, object value)
{
var result = new ValidateResult();
bool testCase = Equals(value, "true"); // Enter "true" to continue for testing purposes.
if (testCase == false)
{
result.IsValid = false;
// A constant should be used with strings that appear more than once in your code.
result.Feedback = TRY_AGAIN;
}
else
{
result.IsValid = true;
// A value must be provided or else the Field will not be populated.
result.Value = value;
}
return result;
}
/// <summary>
/// Here is the method we're using for the PromptAsyncDelegate.
/// </summary>
private static async Task<FormPrompt> PromptAsync(IDialogContext context, FormPrompt prompt,
FAQConversation state, IField<FAQConversation> field)
{
var preamble = context.MakeMessage();
var promptMessage = context.MakeMessage();
if (prompt.GenerateMessages(preamble, promptMessage))
{
await context.PostAsync(preamble);
}
// Here is where we've made a change to the default prompter.
if (state.LastMessage != TRY_AGAIN)
{
await context.PostAsync(promptMessage);
}
state.LastMessage = promptMessage.Text;
return prompt;
}
}

EntityState must be set to null, Created (for Create message) or Changed (for Update message)

In my C# console application I am trying to update an account in CRM 2016. IsFaulted keeps returning true.
The error message it returns when I drill down is the following:
EntityState must be set to null, Created (for Create message) or Changed (for Update message).
Also in case it might cause the fault I have pasted my LINQ query at the bottom.
The answers I get from Google states either that I am mixing ServiceContext and ProxyService (which am not, I am not using it in this context). The others says that I am using context.UpdateObject(object) incorrectly, which I am not using either.
Update: Someone just informed me that the above error is caused because I am trying to return all the metadata and not just the updated data. Still I have no idea how to fix the error, but this information should be helpful.
private static void HandleUpdate(IOrganizationService crmService, List<Entity> updateEntities)
{
Console.WriteLine("Updating Entities: " + updateEntities.Count);
if (updateEntities.Count > 0)
{
try
{
var multipleRequest = new ExecuteMultipleRequest()
{
// Assign settings that define execution behavior: continue on error, return responses.
Settings = new ExecuteMultipleSettings()
{
ContinueOnError = true,
ReturnResponses = true
},
// Create an empty organization request collection.
Requests = new OrganizationRequestCollection()
};
foreach (var account in updateEntities)
{
multipleRequest.Requests.Add(
new UpdateRequest()
{
Target = account
});
}
ExecuteMultipleResponse response = (ExecuteMultipleResponse)crmService.Execute(multipleRequest);
if (response.IsFaulted)
{
int failedToUpdateAccount = 0;
foreach (ExecuteMultipleResponseItem singleResp in response.Responses)
{
if (singleResp.Fault != null)
{
string faultMessage = singleResp.Fault.Message;
var account = ((UpdateRequest)multipleRequest.Requests[singleResp.RequestIndex]).Target;
Log.Error($"Error update acc.id: {account.Id}.Error: {singleResp.Fault.Message}.");
failedToUpdateAccount++;
}
}
Log.Debug($"Failed to update {failedToUpdateAccount} accounts.");
}
else
{
Log.Debug("Execute multiple executed without errors");
}
}
catch (Exception ex)
{
Log.Error($"Error while executing Multiplerequest", ex);
}
}
}
// LINQ below
private static List<Account> GetAllActiveCRMAccounts(CRM2011DataContext CRMcontext)
{
Console.WriteLine("Start Getting CRMExistingAccounts ....");
List<Account> CRMExisterendeAccounts = new List<Account>();
try
{
CRMExisterendeAccounts = (from a in CRMcontext.AccountSet
where a.StateCode == AccountState.Active
where a.anotherVariable == 1
select new Account()
{
my_var1 = a.myVar1,
my_var2 = a.myVar2,
AccountId = a.AccountId,
anotherVar = a.alsoThisVar,
}).ToList();
}
catch (FaultException ex)
{
Log.Debug($"GetCRMExistingAccounts Exception { ex.Message}");
Console.WriteLine("GetCRMExistingAccounts Exception " + ex.Message);
throw new Exception(ex.Message);
}
return CRMExisterendeAccounts;
}
And yes, my variables has different names in my system.
The query returns the object just fine with all the correct data.
You can work around this in one of two ways:
1) Create your CRM2011DataContext with the MergeOption set to MergeOption.NoTracking. Entities loaded from a context that is not tracking will have a null EntityState property.
2) You can create a copy of your Entity and save the copy.

Visual Studio never hits break point in Controller Action

In troubleshooting AddTagsCollection Action behavior in a controller, I have a strange scenario which I have not encountered before, its not even a multi threaded section. The Visual Studio Debugger enters the function till the first line string alert = ""; and even stops at the debugger but never goes on to the other lines!!
public JsonResult AddTagsCollection(int collectionID, string Name, string Description, string Order, bool IsActive, bool RootUseOnly)
{
// Yes hits this break point only then bails out - whats going on??
string Alert = "";
// NEVER hits this break point
if (ProfileTagCollection.GetByName(Name.Trim()).ProfileTagCollectionID > 0)
Alert = "The collection \"" + Name + "\" already exists.";
// NEVER hits this break point!!!
var testme = "test";
// NEVER hits this break point - you get the idea, it just return back to the HTML view??
if (Name.Trim().ToLower().Length == 0)
Alert = "The collection name should not be empty.";
if (Alert != "")
{
RequestResultModel _model = new RequestResultModel();
_model.InfoType = RequestResultInfoType.ErrorOrDanger;
_model.Alert = Alert;
AuditEvent.AppEventWarning(Profile.Member.Email, Alert);
return Json(new
{
NotifyType = NotifyType.DialogInline,
Html = this.RenderPartialView(#"_RequestResultDialogInLine", _model),
}, JsonRequestBehavior.AllowGet);
}
ProfileProfileTagCollection ProfileTagCollection = new ProfileProfileTagCollection();
tagCollection.OrderID = 0;
tagCollection.tagCollectionName = Name;
tagCollection.tagCollectionDescription = Description;
tagCollection.IsActive = IsActive ? 1 : 0;
tagCollection.RootUseOnly = RootUseOnly ? 1 : 0;
tagCollection.Save();
if (collectionID > 0)
AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format("The \"{0}\" profile collection has been updated.", Name));
else
AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format("The \"{0}\" profile collection has been added.",Name));
if (Order != "")
{
Order = Order.Replace("this", tagCollection.tagCollectionID.ToString());
ProfiletagCollections.UpdateOrder(Order);
}
// I have tried passing other combinations to reach here, but why does it not get here
return Json(new {
NotifyType = -1,
Html = "",
}, JsonRequestBehavior.AllowGet);
}
I also tried to lookup the debug windows module, in 2013 its not listed, has it moved... In debug mode, select debug->windows->modules (modules is missing for me)
Can you help me with why the debugger does not hit the break point and what steps I can take to resolve or investigate this?
I think you could use this
You probably are after something like this:
if(System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break(); Of course that will still get
compiled in a Release build. If you want it to behave more like the
Debug object where the code simply doesn't exist in a Release build,
then you could do something like this:
[Conditional("DEBUG")] void DebugBreak() {
if(System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break(); } Then add a call to it in your code.

SharePoint 2010 "unhandled win32 exception occurred in W3WP.EXE"

I am getting an win32 exception that I need help debugging. I have a SharePoint page that has a custom Web Part that when I browse to that page, I get the following message:
In w3wp.dmp the assembly instruction at ntdll!RtlReportCriticalFailure+62 in
C:\Windows\System32\ntdll.dll from Microsoft Corporation has caused an unknown
exception (0xc0000374) on thread 43
Unhandled exception at 0xHEX in w3wp.exe: 0xc0000374:
A heap has been corrupted
I don't really know where to begin debugging this issue and searching the internet has yielded very little results.
I have saved the DMP file and I've loaded it into the Debug Diagnostic Tool for analysis. I don't know what parts are most important, so if someone could tell me which sections I should post, I will post them.
Where I think the problem is:
I have narrowed down the location of where the problem might be. If I don't call these methods, I don't get the error. Is there something wrong with the way I'm accessing the TermStore?
private void GetTerms()
{
using (SPSite site = new SPSite(PhaseListUrl.Value))
{
var session = new TaxonomySession(site);
if (session.TermStores == null || session.TermStores.Count == 0) return;
OfficeDropdown.Items.Clear();
OfficeDropdown.Items.Add("");
var termStore = session
.TermStores
.FirstOrDefault(ts => ts.Groups.Any(g => g.Name == TaxonomyName.Value));
try
{
var group = termStore.Groups[TaxonomyName.Value];
foreach (var ts in group.TermSets)
{
if (!ts.IsAvailableForTagging) continue;
AddTerms(site, termStore, ts.Id, ts.Terms);
}
}
catch (NullReferenceException) { OfficeDropdown.Items.Add("ERROR: Check your Org Term Store Name"); }
catch (ArgumentOutOfRangeException) { OfficeDropdown.Items.Add("ERROR: Check your Org Term Store Name"); }
}
}
private void AddTerms(SPSite site, TermStore termStore, Guid tsId, TermCollection coll)
{
foreach (var t in coll)
{
if (t.IsAvailableForTagging)
{
var wssIds = TaxonomyField.GetWssIdsOfTerm(site, termStore.Id, tsId, t.Id, true, 1000);
if (wssIds.Length != 0)
{
var id = wssIds[0];
var validatedString = string.Format("{0};#{1}{2}{3}", id, t.Name, TaxonomyField.TaxonomyGuidLabelDelimiter, t.Id);
OfficeDropdown.Items.Add(new ListItem(t.Name, validatedString));
}
else
{
int id = -1;
var value = new TaxonomyFieldValue(SPContext.Current.Web.AvailableFields[new Guid("{a64c1f69-c0d6-421a-8c8a-9ef8f459d7a2}")]);
value.TermGuid = t.Id.ToString();
var dummy = value.ValidatedString;
if (dummy != null)
id = value.WssId;
var validatedString = string.Format("{0};#{1}{2}{3}", id, t.Name, TaxonomyField.TaxonomyGuidLabelDelimiter, t.Id);
OfficeDropdown.Items.Add(new ListItem(t.Name, validatedString));
}
}
AddTerms(site, termStore, tsId, t.Terms);
}
}
UPDATE:
The bug was in the TaxonomyField. I was accessing terms cross site collection and the IDs hadn't been generated. Also look out for TermStore IDs not being the same cross site collection (and know where you are calling from and where you are calling to!)
Here are some suggestions.
Pull up ULS Log Viewer and study the logs, if you hit the page and get that error, it should be logged there.
Check the application event logs on the web front-end server(s).
Have you also tried attaching to the W3P.exe process and debug the solution? (Assuming it's not the production environment of course).

Categories