Cannot access a disposed object but the program works - c#

IN WPF project, whenever I try to add selected Student in selected university and display it on assoiated table.
Here is image of my table -
https://i.stack.imgur.com/KUHuF.png
I encounter this problem, once I hit update assosiated button.
public System.Data.Linq.Table<Student> Students
{
get
{
return this.GetTable<Student>();
}
}
The above code is in "Dataclasses1.designer.cs" window.
However, upon restarting the program, selected student is sucessfully added to selected university.
Here is my code -
private void UpdateAssociatedStudent_Click(object sender, RoutedEventArgs e)
{
if(ListUniversity.SelectedItem != null || ListStudent.SelectedItem != null)
{
using (dataContext = new DataClasses1DataContext())
{
UniversityManager universityManager = new UniversityManager
{
UniFK = int.Parse(ListUniversity.SelectedValue.ToString()),
StdFK = int.Parse(ListStudent.SelectedValue.ToString())
};
dataContext.UniversityManagers.InsertOnSubmit(universityManager);
dataContext.SubmitChanges();
}
ShowAssociatedStudents();
Sucess.Text = "Student is sucessfully added to University";
}
}
Edit - Adding image for error
https://i.stack.imgur.com/ApPxd.png

I think that you may need to change this line of code:
if(ListUniversity.SelectedItem != null || ListStudent.SelectedItem != null)
to
if(ListUniversity.SelectedItem != null && ListStudent.SelectedItem != null)

I've solved this issue by running try/catch instead of using 'Using' statement. my edited code looks like this.
//Add selected student from selected university in associated student listbox
private void UpdateAssociatedStudent_Click(object sender, RoutedEventArgs e)
{
if(ListUniversity.SelectedItem != null && ListStudent.SelectedItem != null)
{
try
{
uniManager = new UniversityManager()
{
UniFK = Convert.ToInt32(ListUniversity.SelectedValue),
StdFK = Convert.ToInt32(ListStudent.SelectedValue)
//UniFK = int.Parse(ListUniversity.SelectedItem.ToString()),
//StdFK = int.Parse(ListStudent.SelectedItem.ToString())
};
dataContext.UniversityManagers.InsertOnSubmit(uniManager);
dataContext.SubmitChanges();
ShowAssociatedStudents();
}
catch (FileNotFoundException)
{
Console.WriteLine("File Not Found.");
}
catch (OutOfMemoryException)
{
Console.WriteLine("Out of Memory.");
}
catch (IOException)
{
Console.WriteLine("An I/O error has occured.");
}
}
else
{
Failed.Text = "Please select the missing items from either university or student.";
}
}

Related

Xamarin:Forms: NullReferenceException after popping modal page (No MVVM)

I have a project with a TabbedPage layout. One of the TabbedPages has an ItemsSource with an ItemSelected event handler that pushes a modal page. When I pop the modal page, I receive a System.NullReferenceException: 'Object reference not set to an instance of an object.' break. I am not currently using MVVM, and I have set try/catch blocks on everything on the page I can think of, but I cannot find where the exception is, but Visual Studio seems to be indicating that the exception is not in my code. Call stack:
0xFFFFFFFFFFFFFFFF in System.Diagnostics.Debugger.Mono_UnhandledException_internal
0x1 in System.Diagnostics.Debugger.Mono_UnhandledException at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/corlib/System.Diagnostics/Debugger.cs:125,4
0x20 in Android.Runtime.DynamicMethodNameCounter.1
0x12 in System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:157,13
0x6 in System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__7_0 at /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1021,49
0xC in Android.App.SyncContext.
0xE in Java.Lang.Thread.RunnableImplementor.Run
0x8 in Java.Lang.IRunnableInvoker.n_Run
0x11 in Android.Runtime.DynamicMethodNameCounter.1
My page that causes the NRE:
{
private ObservableCollection<Adventures> adventures;
private List<Character> charactersList;
string played = "No";
string gmed = "No";
public AdventuresPage()
{
InitializeComponent();
}
protected async override void OnAppearing()
{
try
{
var adventureList = await App.client.GetTable<Adventures>().Take(200).ToListAsync();
adventures = new ObservableCollection<Adventures>(adventureList);
AdventuresCollectionView.ItemsSource = adventures;
AdventuresCollectionView.SelectedItem = null;
}
catch (NullReferenceException ex)
{
Console.WriteLine(ex.Message);
}
base.OnAppearing();
}
private async void AdventuresCollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var adventure = AdventuresCollectionView.SelectedItem as Adventures;
string advName = (from a in adventures
where a.Id == adventure.Id
select a.AdventureName).First();
await DetermineCredit(advName);
if(adventure != null)
{
await Navigation.PushModalAsync(new AdventureDetailsPage(adventure, played, gmed));
}
else
{
AdventuresCollectionView.SelectedItem = null;
}
}
private void AdvSearchBar_TextChanged(object sender, TextChangedEventArgs e)
{
var normalizedQuery = e.NewTextValue.ToString().ToLower() ?? "";
AdventuresCollectionView.ItemsSource = adventures.Where(a => a.AdventureName.ToLowerInvariant().Contains(normalizedQuery)).ToList();
}
private async Task DetermineCredit(string name)
{
string advName = name;
charactersList = new List<Character>(await App.client.GetTable<Character>().Where(a => a.AccountId == App.account.Id).ToListAsync());
try
{
for (int c = 0; c < charactersList.Count(); c++)
{
var chara = await App.client.GetTable<Character>().Where(ch => ch.Id == charactersList[c].Id).ToListAsync();
string charId = (from ch in chara
select ch.Id).First().ToString();
var charAdv = await App.client.GetTable<CharAdventures>().Where(ca => ca.AdventureName == advName && ca.CharacterId == charId).ToListAsync();
string creditType = (from ch in charAdv
where advName == ch.AdventureName
select ch.CreditType).FirstOrDefault();
if (string.IsNullOrEmpty(creditType))
{
break;
}
else if (creditType == "Player" && played == "No")
{
played = "Yes";
}
else if (creditType == "GM" && gmed == "No")
{
gmed = "Yes";
}
else
{
break;
}
}
}
catch (NullReferenceException ex)
{
Console.WriteLine(ex.Message);
}
}
}
The stack trace doesn't give me enough information to figure out what is causing the error, and it didn't appear when I stepped through until after the overridden OnAppearing() method completed. I do not see anything that is similar to this in a search, and I don't understand why this doesn't appear when the page is loaded for the first time, but only when popping the modal page. Any suggestions would be appreciated.
I stepped through the load a couple more times, and noticed that after closing the modal, the SelectionChanged event handler was firing.
Commenting out the two AdventuresCollectionView.SelectedItem = null; lines allowed the page to reload without an item selected, and without the NullReferenceException.

Filter not changing on backspace press - radgridview - C#

In my program I have a text box and on text change a filter is applied to my RadGrid. However, on backspace the filter is not reapplied.
private void txt_search_TextChanged_1(object sender, EventArgs e)
{
try
{
CompositeFilterDescriptor searchFilter = new CompositeFilterDescriptor();
searchFilter.FilterDescriptors.Add(new FilterDescriptor("product", FilterOperator.Contains, txt_search.Text));
this.radGridView1.EnableFiltering = true;
this.radGridView1.MasterTemplate.Templates[0].EnableFiltering = true;
this.radGridView1.MasterTemplate.Templates[0].ShowFilteringRow = false;
this.radGridView1.MasterTemplate.ShowFilteringRow = false;
this.radGridView1.MasterTemplate.Templates[0].ShowTotals = true;
this.radGridView1.MasterTemplate.Templates[0].ShowFilterCellOperatorText = false;
if (txt_search.Text != "")
{
this.radGridView1.MasterTemplate.Templates[0].FilterDescriptors.Add(searchFilter);
}
foreach (GridViewRowInfo row in radGridView1.MasterTemplate.Rows)
{
if (row.ChildRows.Count == 0)
{
row.IsVisible = false;
}
else
{
row.IsVisible = true;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Something went wrong searching the grid. Please try again and contact I.T. if this problem persists.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
Is there another function which needs to be generated that is applied on backspace?
This code is taken from another program I have which is written in VB.net and converted. The filter works as it should in the VB version and is reapplied when text is removed etc.
Any help appreciated.

Sql Database retrieving data to UWP

I have my database connected to UWP.
I have this code that works and pulls up all the data that don't have a null name.
private async Task GetStory()
{
MobileServiceInvalidOperationException exception = null;
try
{
// This code gets the entries in the list view by querying the stories table.
items = await storyTable
.Where(todoItem => todoItem.Name != null)
.ToCollectionAsync();
}
catch (MobileServiceInvalidOperationException e)
{
exception = e;
}
if (exception != null)
{
await new MessageDialog(exception.Message, "Error loading items").ShowAsync();
}
else
{
ListViewItems.ItemsSource = items;
}
}
What I want is to load the data if the story is true or false.. on my table I have a column that is bool named isTrue and I set the value of each story to true of false. I am trying to get the true stories to show but the exception pops up.
Below is the code that doesn't work.. I just changed the .name != null to .isTrue !=false I also tried .isTrue == true, but nothing seems to work..
private async Task GetStory()
{
MobileServiceInvalidOperationException exception = null;
try
{
// This code gets the entries in the list view by querying the stories table.
items = await storyTable
.Where(todoItem => todoItem.isTrue != false)
.ToCollectionAsync();
}
catch (MobileServiceInvalidOperationException e)
{
exception = e;
}
if (exception != null)
{
await new MessageDialog(exception.Message, "Error loading items").ShowAsync();
}
else
{
ListViewItems.ItemsSource = items;
}
}
Can anybody help?
Thanks in advance

Skydrive wp7 App: GetAsync method stopped working

On my windows phone 7 Mango app I use the Microsoft.Live and Microsoft.Live.Controls references to download and upload on Skydrive. Logging in and uploading files works fine but whenever I call the "client.GetAsync("/me/skydrive/files");" on the LiveConnectClient the Callback result is empty just containing the error: "An error occurred while retrieving the resource. Try again later."
I try to retrieve the list of files with this method.
This error suddenly occured without any change on the source code of the app (I think..) which worked perfectly fine for quite a while until recently. At least I didn't change the code section for up- or downloading.
I tried out the "two-step verification" of Skydrive, still the same: can log in but not download.
Also updating the Live refercences to 5.5 didn't change anything.
Here is the code I use. The error occurs in the "getDir_Callback" in the "e" variable.
Scopes (wl.skydrive wl.skydrive_update) and clientId are specified in the SignInButton which triggers "btnSignin_SessionChanged".
private void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
connected = true;
processing = true;
client = new LiveConnectClient(e.Session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(UploadCompleted);
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompleted);
client.DownloadProgressChanged += new EventHandler<LiveDownloadProgressChangedEventArgs>(client_DownloadProgressChanged);
infoTextBlock.Text = "Signed in. Retrieving file IDs...";
client.GetAsync("me");
}
else
{
connected = false;
infoTextBlock.Text = "Not signed into Skydrive.";
client = null;
}
}
private void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
if (e.Error == null)
{
client.GetCompleted -= new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.GetCompleted += getDir_Callback;
client.GetAsync("/me/skydrive/files");
client_id = (string)e.Result["id"];
if (e.Result.ContainsKey("first_name") && e.Result.ContainsKey("last_name"))
{
if (e.Result["first_name"] != null && e.Result["last_name"] != null)
{
infoTextBlock.Text = "Hello, " +
e.Result["first_name"].ToString() + " " +
e.Result["last_name"].ToString() + "!";
}
}
else
{
infoTextBlock.Text = "Hello, signed-in user!";
}
}
else
{
infoTextBlock.Text = "Error calling API: " +
e.Error.ToString();
}
processing = false;
}
public void getDir_Callback(object s, LiveOperationCompletedEventArgs e)
{
client.GetCompleted -= getDir_Callback;
//filling Dictionary with IDs of every file on SkyDrive
if (e.Result != null)
ParseDir(e);
if (!String.IsNullOrEmpty(e.Error.Message))
infoTextBlock.Text = e.Error.Message;
else
infoTextBlock.Text = "File-IDs loaded";
}
Yo shall use client.GetAsync("me/SkyDrive/files", null) in place of client.GetAsync("me");
This is my code and it works fine.
private void btnSignIn_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
try
{
if (e.Session != null && e.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(e.Session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_GetCompleted);
client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_UploadCompleted);
client.GetAsync("me/SkyDrive/files", null);
client.DownloadAsync("me/SkyDrive", null);
canUpload = true;
ls = e.Session;
}
else
{
if (client != null)
{
MessageBox.Show("Signed out successfully!");
client.GetCompleted -= client_GetCompleted;
client.UploadCompleted -= client_UploadCompleted;
canUpload = false;
}
else
{
canUpload = false;
}
client = null;
canUpload = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void client_GetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
try
{
List<System.Object> listItems = new List<object>();
if (e.Result != null)
{
listItems = e.Result["data"] as List<object>;
for (int x = 0; x < listItems.Count(); x++)
{
Dictionary<string, object> file1 = listItems[x] as Dictionary<string, object>;
string fileName = file1["name"].ToString();
if (fileName == lstmeasu[0].Title)
{
folderID = file1["id"].ToString();
folderAlredyPresent = true;
}
}
}
}
catch (Exception)
{
MessageBox.Show("An error occured in getting skydrive folders, please try again later.");
}
}
It miraculously works again without me changing any code. It seems to be resolved on the other end. I have no clue what was wrong.

goto in c# and its usage

I have a subroutine. It comapares whether values are empty then doing something. For example, if they are empty, then warnings are raised.
The code works fine. But when value are not empty, the warnings are still pop out. Please help me to correct the logic.
Thanks.
private void btnNew_Click(object sender, EventArgs e)
{
try
{
if (txtbox1.Text.ToString().Trim() == string.Empty)
{
goto Msg1;
}
if (txtbox2.Text.ToString().Trim() == string.Empty)
{
goto Msg2;
}
DataRow dr = mydataSet.Tables[0].NewRow();
dr["Descript"] = txtbox1.Text;
dr["Abbr"] = txtbox2.Text;
dr["SortOrder"] = Convert.ToDecimal(numericOrder.Value);
if (SortOrders.Contains((decimal)dr["SortOrder"]))
{
goto Msg3;
}
mydataSet.Tables[0].Rows.Add(dr);
dgv.DataSource = mydataSet.Tables[0];
Msg1:
MessageBox.Show("Description is required.");
Msg2:
MessageBox.Show("Abbr is required.");
Msg3:
MessageBox.Show("Please select another one, this one is already used.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
From the above code, you see. if txtbox1 has some value, the program still displays Msg1. I want to avoid it.
Because labels are just labels, and code after them is executed sequentially.
Why can't you do just this:
try
{
if (txtbox1.Text.ToString().Trim() == string.Empty)
{
MessageBox.Show("Description is required.");
return;
}
if (txtbox2.Text.ToString().Trim() == string.Empty)
{
MessageBox.Show("Abbr is required.");
return;
}
DataRow dr = mydataSet.Tables[0].NewRow();
dr["Descript"] = txtbox1.Text;
dr["Abbr"] = txtbox2.Text;
dr["SortOrder"] = Convert.ToDecimal(numericOrder.Value);
if (SortOrders.Contains((decimal)dr["SortOrder"]))
{
MessageBox.Show("Please select another one, this one is already used.");
return;
}
mydataSet.Tables[0].Rows.Add(dr);
dgv.DataSource = mydataSet.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
It's so much more readable.
Restructure your code to avoid goto - it is a relic and not much use in a properly object oriented codebase.
Returning from the method, throwing exceptions or building an errors dictionary are all better options than using goto.
For example, you can have a List<string> errors which you add to when you get an error condition.
If it is empty, no errors were encountered, if it isn't, there were.
This is a good case were goto is the wrong way to go. Use something like this instead.
private void btnNew_Click(object sender, EventArgs e)
{
try
{
bool error = false;
if (txtbox1.Text.ToString().Trim() == string.Empty)
{
MessageBox.Show("Description is required.");
error = true;
}
if (txtbox2.Text.ToString().Trim() == string.Empty)
{
MessageBox.Show("Abbr is required.");
error = true;
}
if (SortOrders.Contains(Convert.ToDecimal(numericOrder.Value)
{
MessageBox.Show("Please select another one, this one is already used.");
error = true;
}
if(error)
return;
DataRow dr = mydataSet.Tables[0].NewRow();
dr["Descript"] = txtbox1.Text;
dr["Abbr"] = txtbox2.Text;
dr["SortOrder"] = Convert.ToDecimal(numericOrder.Value);
mydataSet.Tables[0].Rows.Add(dr);
dgv.DataSource = mydataSet.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Edit
Just figured that my code didn't actually do the same as his first sample since it only displayed the first error no matter how many that occured. Updated my sample to accomodate for that.
I've always been taught to avoid goto like the plague, and it's something I've followed for years. I've never even considered it to be an option when writing code.
Thinking about it though, I did read an article a few years ago (which I can't find now) which said you could credibly use gotos only if you used it to jump down code, and not up: a rule that is stuck to here.
Check here for more info: Does anyone still use [goto] in C# and if so why?
There are better ways of using goto statement, for instacne using "return" (when used in the middle of a method), "break" and "continue". Have you ever used one of these?
private void btnNew_Click(object sender, EventArgs e)
{
try
{
var description = txtbox1.Text.Trim();
if (string.IsNullOrEmpty(description))
{
MessageBox.Show("Description is required.");
return;
}
var abbr = txtbox2.Text.Trim();
if (string.IsNullOrEmpty(abbr))
{
MessageBox.Show("Abbr is required.");
return;
}
var numericOrderValue = Convert.ToDecimal(numericOrder.Value);
if (SortOrders.Contains(numericOrderValue)
{
MessageBox.Show("Please select another one, this one is already used.");
return;
}
DataRow dr = mydataSet.Tables[0].NewRow();
dr["Descript"] = description;
dr["Abbr"] = abbr;
dr["SortOrder"] = numericOrderValue;
mydataSet.Tables[0].Rows.Add(dr);
dgv.DataSource = mydataSet.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnNew_Click(object sender, EventArgs e)
{
try
{
if (txtbox1.Text.ToString().Trim() == string.Empty)
{
MessageBox.Show("Description is required.");
}
if (txtbox2.Text.ToString().Trim() == string.Empty)
{
MessageBox.Show("Abbr is required.");
}
DataRow dr = mydataSet.Tables[0].NewRow();
dr["Descript"] = txtbox1.Text;
dr["Abbr"] = txtbox2.Text;
dr["SortOrder"] = Convert.ToDecimal(numericOrder.Value);
if (SortOrders.Contains((decimal)dr["SortOrder"]))
{
MessageBox.Show("Please select another one, this one is already used.");
}
mydataSet.Tables[0].Rows.Add(dr);
dgv.DataSource = mydataSet.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Try this. It works.

Categories

Resources