Sql Database retrieving data to UWP - c#

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

Related

Cannot access a disposed object but the program works

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.";
}
}

Correct way to handle mulitple http Request async with error handling

The solution works, but is there a better way to handle multiple requests like this with the errorhandling.
The below code describes what i want to do, and absolutely works. But I'm sure there is a better way to go about the issue?
I've tried other options as well but it fails as some of the requests will return a 404.
public async Task<List<Bruker>> TryGetContactsByContactIds(List<AZContact> contacts)
{
var tasks = contacts.Select(c => TryGetContactAsync(c.Email)).Where(c => c.Result != null);
try
{
var tasksresult = await Task.WhenAll(tasks);
return tasksresult.ToList();
}
catch (Exception e)
{
_logger.Error("unable to fetch all", e);
}
return new List<Bruker>();
}
public async Task<Bruker> TryGetContactAsync(string userId)
{
try
{
var user = await _brukereClient.GetAsync(userId);
return user;
}
catch (SwaggerException e)
{
if (e.StatusCode == 404)
{
_logger.Info($"user with Id {userId} does not exist");
}
else
{
_logger.Error("Unable to fetch user", e);
}
}
return null;
}
You are probably dealing with a feature/limitation of await, that throws only one of the aggregated exceptions of the awaited task (the WhenAll task in this case). You must enumerate all the tasks to handle each individual exception.
try
{
var tasksresult = await Task.WhenAll(tasks);
return tasksresult.ToList();
}
catch (Exception e)
{
foreach (var task in tasks)
{
if (task.IsFaulted)
{
var taskException = task.Exception.InnerException;
// ^^ Assuming that each task cannot have more than one exception inside its AggregateException.
if (taskException is SwaggerException swaggerException)
{
if (swaggerException.StatusCode == 404)
{
_logger.Info($"user with Id {userId} does not exist");
}
else
{
_logger.Error("Unable to fetch user", swaggerException);
}
}
else
{
_logger.Error("An unexpected task error occurred", taskException);
}
}
}
if (!tasks.Any(t => t.IsFaulted))
{
_logger.Error("A non task-related error occurred", e);
}
}

Splitting data access and catching data to form

In my project I'm trying to write code that will be nice to understand.
I currently split my data access functions in a seperate class.
What I'm trying to achieve however, is to catch the errors back to my form. I am not getting this currently and I was wondering why.
In my form I have the following code:
private void btn_Save_ItemClick(object sender, ItemClickEventArgs e)
{
if (dal.updatePerson(ObjectAfterSaving))
{
MessageBox.Show("Updated!");
}
else
{
MessageBox.Show("error");
};
}
In my dal object (derived from the DataAccess_Person class), I have the following method:
public bool updatePerson(Person p)
{
conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Database"].ConnectionString);
SqlCommand command = new SqlCommand(#"UPDATE Person
SET PersonName = #PersonName
WHERE PersonID = #PersonID", conn);
command.Parameters.Add("#PersonName", SqlDbType.VarChar).Value = p.Name
{
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
int a = command.ExecuteNonQuery();
conn.Close();
if (a > 0)
{
return true;
}
else
{
return false;
}
}
catch (SqlException ex)
{
ex.ToString();
return false;
}
}
}
My question is: let's say if my method falls in the catch. Will my front end (form) show it (Sql Exception for example) ? Or will i just get 'error' ? And If I will just get error, how I can improve my code to show the Exception instead of error?
A simple way is to remove the try catch from your DAL and add it to the form. For example:
private void btn_Save_ItemClick(object sender, ItemClickEventArgs e)
{
var result = "Success";
try
{
dal.updatePerson(ObjectAfterSaving);
}
catch (SqlException sqlEx)
{
result = sqlEx.Message;
}
catch (Exception ex)
{
result = ex.Message;
}
MessageBox.Show(result);
}
Just note that there's a lot of ways you can do this. My preference is to not include DAL specific exception types in my UI. Instead I may return a custom result type that has an errorcode and message and let my UI display that or generate a custom message based on the error code.
You‘ll just get „error“ in case of a SqlException. All other exceptions will crash your program if you don‘t have a global exception handler. If you want to show the error message you could introduce an out variable for the error message:
bool successful = MyMethod(out string errorMessage)
if (!successful)
{
MessageBox.Show(errorMessage);
}
public bool MyMethod(out string errorMessage)
{
errorMessage = "";
try
{
// do some stuff
return true;
}
catch(Exception ex)
{
errorMessage = ex.Message;
return false;
}
}

DBcontext.SaveChanges keeps returning 0 when updating

I'm currently trying to do a really simple function that updates a category using LINQ. However dbContext.SaveChanges() always returns 0 rows updated even when I hardcode the categoryId to update which is really frustrating. I've already tried many forms of debugging but fail to find the problem. If anyone can help me figure out my dumb mistake, it would be greatly appreciated!
Things I've tried,
- Trying to see if row with that category_Id exists, always returns 1 which is correct.
var count = (from c in dbContext.RecipeCategories
where c.Category_Id == categoryToEdit
select c).Count();
Removing myCategory instead of trying to update it, works as well. It seems like only the update does not work.
dbContext.RecipeCategories.Remove(myCateogry);
My DALayer for category functions
public bool EditCategory(int categoryToEdit, RecipeCategory newCategoryInfo)
{
RecipeXchangeDBContext dbContext = new RecipeXchangeDBContext();
RecipeCategory myCategory = new RecipeCategory();
bool status = false;
myCategory = (from c in dbContext.RecipeCategories
where c.Category_Id == categoryToEdit
select c).First();
myCategory.Category_Name = newCategoryInfo.Category_Name;
myCategory.Description = newCategoryInfo.Description;
myCategory.CatGroup_Id = newCategoryInfo.CatGroup_Id;
try
{
if (dbContext.SaveChanges() == 1)
status = true;
else
status = false;
}
catch (InvalidOperationException ex)
{
status = false;
}
return status;
}
My attempt to call the function, always goes to else block, dbContext.SaveChanges() returns 0 with no exceptions thrown.
protected void btnEditCategory_Click(object sender, EventArgs e)
{
if (Request.QueryString["categoryId"] != null)
{
CategoryDAL categoryDAL = new CategoryDAL();
RecipeCategory myCategory = new RecipeCategory();
try
{
addDiv.Attributes["class"] = "hidden";
editDiv.Attributes["class"] = "display";
int categoryToEdit = Convert.ToInt32(Request.QueryString["categoryId"]);
myCategory.Category_Name = tbEditCategoryName.Text;
myCategory.Description = tbEditCategoryDescription.Text;
myCategory.CatGroup_Id = Convert.ToInt32(ddlEditCategoryGroupList.SelectedValue);
try
{
bool editStatus = categoryDAL.EditCategory(categoryToEdit, myCategory);
if (editStatus)
{
HttpContext.Current.Session["editStatus"] = "Successful";
Response.Redirect("~/Admin/ManageCategories.aspx");
}
else
{
lblEditStatus.Text = "Unable to update category, please try again";
lblEditStatus.CssClass = "alert-danger";
}
}
catch (Exception ex)
{
lblEditStatus.Text = Convert.ToString(ex);
lblEditStatus.CssClass = "alert-danger";
}
}
catch (Exception ex)
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Invalid categoryId.";
}
}
else
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Nothing to update.";
}
}
Update ** Seems like this is what's causing the problem. If the values of the form are prepopulated it doesn't seem to allow me to update the object. If I comment out the part where it populates the form. The update function works normally. Can anyone help me figure out why prepopulating the form causes the update to fail?
protected void Page_Load(object sender, EventArgs e)
{
// Populate Edit Fields
if (Request.QueryString["categoryId"] != null)
{
CategoryDAL categoryDAL = new CategoryDAL();
RecipeCategory myCategory = new RecipeCategory();
try
{
addDiv.Attributes["class"] = "hidden";
editDiv.Attributes["class"] = "display";
int categoryToGet = Convert.ToInt32(Request.QueryString["categoryId"]);
myCategory = categoryDAL.GetCategory(categoryToGet);
tbEditCategoryName.Text = myCategory.Category_Name;
tbEditCategoryDescription.Text = myCategory.Description;
ddlEditCategoryGroupList.SelectedValue = Convert.ToString(myCategory.CatGroup_Id);
}
catch(Exception ex)
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Could not get Category Info, please try again.";
}
}
}

Returning value by a thread

Having this :
public Item_DataColl invoke_command_READ(string UCPTName)
{
networkingThread = new Thread(new ParameterizedThreadStart(thread_command_READ));
networkingThread.Start(new readingThreadParameter(UCPTName));
}
private Item_DataColl thread_command_READ_result(object parameter)
{
readingThreadParameter p = parameter as readingThreadParameter;
Item item;
if (p.UCPT_Name != null)
{
Item_DataColl resultSet;
try
{
OnProgressBarUpdate(progressBar.UnknownEnd);
resultSet = connector.command_READ(p.UCPT_Name);
readOperationDone(resultSet);
OnConsoleWriting(string.Format("[READING] Lecture réussie : {0} = {1}", ((Dp_Data)resultSet.Item[0]).UCPTname, ((Dp_Data)resultSet.Item[0]).UCPTvalue[0].Value), ILonConnectorConsoleResultType.RESULT);
return resultSet; // HERE, I WANT TO RETURN RESULT
}
catch (Exception e)
{
OnConsoleWriting(e.ToString(), ILonConnectorConsoleResultType.ERROR);
}
finally
{
OnProgressBarUpdate(progressBar.Invisible);
}
}
}
I'm trying to execute a SOAP request and to send the result. To make the application "non-blocking", i've used Thread.
The soap request works perfectly, but i have trouble to send a result just after the end of the thread. I will have to keep track of it and when the thread is over, to send back the result to another class.
How can i perform this ?
Well.. this solution CAN BE WRITTEN WAY BETTER.. but I'm currently working with the code you already posted.
The approach - using a callback (with a delegate):
First - declare a delegate in your class scope
private Action<Item_DataColl> OnResultSetComplete;
Second - assign the delegate with some function BEFORE calling your thread
public Item_DataColl invoke_command_READ(string UCPTName)
{
OnResultSetComplete = (resukts) =>
{
// DO SOMETHING HERE
};
networkingThread = new Thread(new ParameterizedThreadStart(thread_command_READ));
networkingThread.Start(new readingThreadParameter(UCPTName));
}
Finally - change your read result function:
private Item_DataColl thread_command_READ_result(object parameter)
{
readingThreadParameter p = parameter as readingThreadParameter;
Item item;
if (p.UCPT_Name != null)
{
Item_DataColl resultSet;
try
{
OnProgressBarUpdate(progressBar.UnknownEnd);
resultSet = connector.command_READ(p.UCPT_Name);
readOperationDone(resultSet);
OnConsoleWriting(string.Format("[READING] Lecture réussie : {0} = {1}", ((Dp_Data)resultSet.Item[0]).UCPTname, ((Dp_Data)resultSet.Item[0]).UCPTvalue[0].Value), ILonConnectorConsoleResultType.RESULT);
if (OnResultSetComplete != null) OnResultSetComplete(resultSet);
}
catch (Exception e)
{
OnConsoleWriting(e.ToString(), ILonConnectorConsoleResultType.ERROR);
}
finally
{
OnProgressBarUpdate(progressBar.Invisible);
}
}
}

Categories

Resources