Windows 8/RT delete from sqlite using linq - c#

I have SQLite database in isolated storage in Windows Store App.
I use SQLite for Windows Runtime
When i want to delete all table entry I use follow method:
public static async void DeleteAllProjects()
{
var storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("myDb.sqlite");
using (var db = new SQLiteConnection(storageFile.Path))
{
try
{
db.DeleteAll<Projects>();
}
catch
(Exception ex)
{
Debug.WriteLine("Delete error " + ex.Message);
}
}
}
All work like a charm.
But when i need to delete part of entries:
public static async void Delete(List<Projects> projects)
{
var storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("myDb.sqlite");
using (var db = new SQLiteConnection(storageFile.Path))
{
try
{
foreach (var project in projects)
{
var existingProject = (db.Table<Projects>().Where(
p => p.id == project.Id)).FirstOrDefault();
if (existingProject != null)
{
db.Delete<Projects>(existingProject);
}
}
}
catch
(Exception ex)
{
Debug.WriteLine("Delete error " + ex.Message);
}
}
}
I handled exeption with
ex.Message = "Cannot delete Projects: it has no PK" string
Can somebody help me?

Related

Cannot perform runtime binding on a null reference Exception with var type

I am trying to fetch data from CRM using this API. I get an error
Runtime binding on a null reference
whenever I try to get value from data.fullname. Is there any way I can fix it?
Thanks
var response = httpClient.GetAsync("contacts?$select=fullname,emailaddress1").Result;
if (response.IsSuccessStatusCode)
{
var accounts = response.Content.ReadAsStringAsync().Result;
var jRetrieveResponse = JObject.Parse(accounts);
dynamic collContacts = JsonConvert.DeserializeObject(jRetrieveResponse.ToString());
try
{
foreach (var data in collContacts.value)
{
// You can change as per your need here
if (data.fullname.Value != null)
{
success[i] = data.fullname.Value;
}
i ++;
}
}
catch (Exception)
{
throw;
}
}
Replace
if (data.fullname.Value != null)
with this
if (!String.IsNullOrWhiteSpace(data.fullname.Value))
OR Replace
try
{
foreach (var data in collContacts.value)
{
// You can change as per your need here
if (data.fullname.Value != null)
{
success[i] = data.fullname.Value;
}
i ++;
}
}
catch (Exception)
{
throw;
}
With
try
{
foreach (var data in collContacts.value)
{
success[i] = data?.fullname?.Value;
i ++;
}
}
catch (Exception)
{
throw;
}

Get EventMessage from message in MS Graph API with C#

I am trying to Get EventMessage from Message in MS Graph API with C# but every time it is showing type as a message instead of EventMessage. Below are the code:-
public static Graph.MailFolderMessagesCollectionPage ReadInbox()
{
GetAuthenticatedClient();
var result = new Graph.MailFolderMessagesCollectionPage();
List<Graph.QueryOption> options = new List<Graph.QueryOption>
{
new Graph.QueryOption("$expand","microsoft.graph.eventMessage/event"),
new Graph.QueryOption("$filter","isread eq false")
};
try
{
var response = graphClient.Me.MailFolders.Inbox.Messages.Request(options).OrderBy("receivedDateTime DESC").GetAsync();
result = response.Result as Graph.MailFolderMessagesCollectionPage;
}
catch (Exception ex)
{ }
Call the above method ReadInbox to get type and perform some action.
var appointments = ReadInbox();
if (appointments != null)
{
foreach (dynamic request in appointments)
{
try
{
if (request.GetType().Name.Contains("EventMessage"))
{
}
else if (request.GetType().Name == "Message")
{
}
}
catch (Exception ex)
{
}
}
}
Use the IsInstanceOfType method to identify if its an eventMessage. You can also remove the expand option from the query option since eventMessages are fetched anyway as part of the get Messages call.
if (appointments != null)
{
foreach (dynamic request in appointments)
{
try
{
if (typeof(EventMessage).IsInstanceOfType(request))
{
Console.WriteLine("Is an event");
Console.WriteLine(request);
}
}
catch (Exception ex)
{
}
}
}

AutoRest Targeting web api version

I have not implemented versioning to my api yet, as wanted to get some more info first.
I am using asp.net web api, and integrating into a WPF application, using AutoRest.
Its been running for some months now, but I'm looking to use versioning with the api.
With a typical call from WPF to the api, is there a way to target particular versions of the api?
public async Task<ObservableCollection<EventsDTO>> GetEvents(bool ShowInActive)
{
try
{
CheckCredentials.CheckValidCredentials();
using (var db = new BuxtedAPI(CheckCredentials.RestCredentials))
{
var res = await db.GetEventsAsync(ShowInActive).ConfigureAwait(false);
var obs = new ObservableCollection<EventsDTO>(res);
return obs;
}
}
catch (Exception ex)
{
logger.Error(ex);
return null;
}
}
Thanks in advance.
If anyone else has this problem.
public async Task<ObservableCollection<EventsDTO>> GetEvents(bool ShowInActive)
{
try
{
CheckCredentials.CheckValidCredentials();
using (var db = new BuxtedAPI(CheckCredentials.RestCredentials))
{
db.HttpClient.DefaultRequestHeaders.Add("X-Version", "2.0");
var res = await db.GetEventsAsync(ShowInActive).ConfigureAwait(false);
var obs = new ObservableCollection<EventsDTO>(res);
return obs;
}
}
catch (Exception ex)
{
logger.Error(ex);
MessageBox.Show(
$"{ex.Message}{Environment.NewLine}{ex.InnerException?.ToString() ?? ""}");
return null;
}
}
and on the controller
public class EventV2Controller : ApiController
{
[ApiVersion("2.0")]
[RoutePrefix("api/events")]
and the config.
config.AddApiVersioning(cfg =>
{
cfg.DefaultApiVersion = new ApiVersion(1, 0);
cfg.AssumeDefaultVersionWhenUnspecified = true;
cfg.ReportApiVersions = true;
cfg.ApiVersionReader = new HeaderApiVersionReader("X-Version");
});

how to remove data from local db (sqlite) using code behind wpf?

I want to do something like when user click a button then it will remove data from database ( it will only have one data every time user run the system). the problem is I try to use this code to remove the data but it does not work.
public void RemoveOrder(Order order)
{
try
{
using (tempPosOrderPaymentDBContext db = new tempPosOrderPaymentDBContext ())
{
db.Orders.Remove(order);
db.SaveChanges();
}
}
catch (Exception ex)
{
CustomExceptionHandling customExceptionHandling = new CustomExceptionHandling();
customExceptionHandling.CustomExHandling(ex.ToString());
}
}
when I try to add the data to database using the same code but only change the remove to Add it working fine. but only with this remove thing it does not work.
Can you try this and it should work:
public void RemoveOrder(Order order)
{
try
{
using (tempPosOrderPaymentDBContext db = new tempPosOrderPaymentDBContext ())
{
var orderInDb = db.Orders.First(x=> x.OrderId == order.OrderId);
db.Orders.Remove(orderInDb);
db.SaveChanges();
}
}
catch (Exception ex)
{
CustomExceptionHandling customExceptionHandling = new CustomExceptionHandling();
customExceptionHandling.CustomExHandling(ex.ToString());
}
}

Task<T>.Factory.StartNew in ASP.NET MVC

I'm stuck with a problem. I need help...
In general, I have an ASP.NET MVC 5 project. When a user clicks on "Save" button, I run some code in a new created task. I need to know the result of operation, so I return the instance of my class ChangesMade. Then I serialze the object to JSON format and pass to a view. Then I check if result is true, I open an url in a new window.
So, in my controller I have the following:
public async Task<ActionResult> Save(here some parameters)
{
var changes = await _model.SaveAsync(some parameters);
return NewtownJson(changes);
}
The main saving logic is the following:
public async Task<ChangesMade> SaveAsync(some parameters here)
{
var data = (await _model.GetData(some parameter)).ToList();
// create a task of ChangesMade that contains public bool property MemoAdded
// that I need to pass to a view to know the result of operation
var task = Task<ChangesMade>.Factory.StartNew(() =>
{
ChangesMade changes = new ChangesMade();
try
{
using (var tr = new TransactionScope())
{
// some code here omitted for simplicity…
// if (someCondition == true) changes.MemoAdded = true;
tr.Complete();
}
return changes;
}
catch (Exception ex)
{
throw ex;
}
});
try
{
task.Wait();
}
catch (AggregateException ex)
{
string msg = "";
msg= ex.Flatten().InnerExceptions
.Where(e => e != null)
.Select(e => e.Message)
.Aggregate(msg, (current, message) => current + " " + message + ";")
.TrimEnd(';');
throw new Exception(msg);
}
return task.Result;
}
I publish the project on two sites on IIS. The first works fine. But the second doesn't - by some reason, it always returns changes.MemoAdded false to the view.
I can't find out a reason of that. I don't have a clue what to do ...

Categories

Resources