I receive this error when trying to remove entries from the table with EFC
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: The database operation was expected to affect 1 row(s), but actually affected 30 row(s); data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.
This is my code:
https://paste.mod.gg/xlynuworjmmf/0
using MySqlConnector;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using MySql.EntityFrameworkCore;
namespace Flanium_Agent
{
public class AgentContext : DbContext
{
public DbSet<Agent> agent { get; set; }
public DbSet<AgentRequest> agentRequest { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL("Server=localhost;User ID=root;Database=orchestration_db");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Agent>().HasKey(a => a.Station);
modelBuilder.Entity<Agent>().ToTable("agents");
modelBuilder.Entity<AgentRequest>().HasKey(a => a.Station);
modelBuilder.Entity<AgentRequest>().ToTable("agent_requests");
}
}
public class Agent
{
public string Station { get; set; }
public string Process { get; set; }
public string Actions { get; set; }
public string Started { get; set; }
public string Finished { get; set; }
public string Status { get; set; }
}
public class AgentRequest
{
public string Station { get; set; }
public string Request { get; set; }
}
public class Agency : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private bool ProcessRunning = false;
private List<string> RequestList = new List<string>();
public string Station { get; set; }
public string Process { get; set; }
public string Actions { get; set; }
public string Started { get; set; }
public string Finished { get; set; }
public string Status { get; set; }
public string Request { get; set; }
private Grid DisplayGrid { get; set; }
private Window appWindow { get; set; }
public Grid GetDisplayGrid()
{
return DisplayGrid;
}
public Agency InsertAgentToGrid(Window mainWindow)
{
DisplayGrid = new Grid();
var headerRowDefinition = new RowDefinition();
headerRowDefinition.Height = new GridLength(50);
DisplayGrid.RowDefinitions.Add(headerRowDefinition);
for (var index = 0; index < GetType().GetProperties().Length; index++)
{
var property = GetType().GetProperties()[index];
var header = new TextBlock();
var column = new ColumnDefinition();
header.Text = property.Name;
header.HorizontalAlignment = HorizontalAlignment.Center;
header.VerticalAlignment = VerticalAlignment.Center;
header.FontSize = 16;
header.FontWeight = FontWeights.Medium;
Grid.SetRow(header, 0);
Grid.SetColumn(header, index);
DisplayGrid.ColumnDefinitions.Add(column);
DisplayGrid.Children.Add(header);
}
var contentRowDefinition = new RowDefinition();
contentRowDefinition.Height = GridLength.Auto;
DisplayGrid.RowDefinitions.Add(contentRowDefinition);
for (var index = 0; index < GetType().GetProperties().Length; index++)
{
var propertyValue = GetType().GetProperties()[index];
var content = new TextBlock();
content.HorizontalAlignment = HorizontalAlignment.Center;
content.VerticalAlignment = VerticalAlignment.Center;
content.FontSize = 12;
content.TextWrapping = TextWrapping.Wrap;
Grid.SetRow(content, 1);
Grid.SetColumn(content, index);
DisplayGrid.Children.Add(content);
var myBinding = new Binding(propertyValue.Name)
{
Source = this,
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
content.SetBinding(TextBlock.TextProperty, myBinding);
}
DisplayGrid.HorizontalAlignment = HorizontalAlignment.Stretch;
DisplayGrid.VerticalAlignment = VerticalAlignment.Top;
DisplayGrid.Margin = new Thickness(0, 25, 0, 0);
(mainWindow.Content as Grid).Children.Add(DisplayGrid);
appWindow = mainWindow;
return this;
}
private string[] GetPackages()
{
var packagesArray = new List<string>();
var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var pathString = Path.Combine(desktopPath, "Flanium Agent Data");
var packageFolders = Directory.GetDirectories(pathString);
foreach (var packFolder in packageFolders)
{
var versions = Directory.GetDirectories(packFolder);
if (versions.Length != 0)
{
packagesArray.AddRange(versions.Select(version => version.Split('\\').Last())
.Select(versionName => packFolder.Split('\\').Last() + "\\" + versionName));
packagesArray = packagesArray.Select(x => x = pathString + "\\" + x).ToList();
}
}
return packagesArray.ToArray();
}
public Agency(string station, string process, string actions, string started, string finished, string status)
{
try
{
using (var context = new AgentContext())
{
context.agent.Add(new Agent
{Station = station, Process = process, Actions = actions, Started = started, Finished = finished, Status = status});
// Saves changes
context.SaveChanges();
}
Station = station;
Process = process;
Actions = actions;
Started = started;
Finished = finished;
Status = status;
}
catch (Exception e)
{
}
}
public void RemoveAgent()
{
using (var context = new AgentContext())
{
context.agent.Where(x=> x.Station == Station).ToList().ForEach(x=> context.agent.Remove(x));
// Saves changes
context.SaveChanges();
}
}
}
}
I followed a tutorial on the internet on how to use EFC by the teeth and for some euclidean reason, as always, the code works for others and the same code does not work when I try it out.
modelBuilder.Entity<Agent>().HasKey(a => a.Station);
So you have an entity Agent, about which you tell Entity Framework that it has a primary key column named "station".
You have a database with at least 30 records in it, and at least 30 of those records have the same value for the station column.
So despite you telling EF that station is the primary key, it isn't. So EF generates the query:
DELETE FROM agent WHERE station=#station
And the database engine happily removes all 30 records for which the station equals the station of the first record it encounters, and reports this, then EF throws, because it expected one record to be deleted, not 30.
The solution: configure the actual primary key as key, or if there isn't any, create one.
Related
dotNet Core 5 C# Web API project, Service class adds objects (based on a viewmodel) to a list. Debugging shows all data correct as the object is built and added to the List, but the returned result has multiple (matching the count it should have) copies of the last item added only. Service code and viewmodel code below. What am I missing?
using FS.Data.Repositories;
using FS.Models;
using FS.ViewModels;
using FS.ViewModels.APVendor;
using Microsoft.Extensions.Options;
using NLog;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace FS.Services
{
public class GLAccountSetService : IGLAccountSetService
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
private readonly IOptions<AppSettingsModel> AppSettings;
private readonly HttpClient Client;
GlAccountSetResponseViewModel result = new GlAccountSetResponseViewModel();
public GLAccountSetService(HttpClient client, IOptions<AppSettingsModel> app)
{
Client = client; //?? throw new ArgumentNullException(nameof(client));
AppSettings = app;
}
public async Task<GlAccountSetResponseViewModel> GetGLAccountSets(IList<GlAccountSetRequestViewModel> req, IAPCorpRepository apcr)
{
result.GlAccountSetViewModels = new List<GlAccountSetViewModel>();
result.SuccessErrorWarningResult = new SuccessErrorWarningResult();
GlAccountSetViewModel accountSet = new GlAccountSetViewModel();
string payorID = "";
string payeeID = "";
string payorCashAccount = "";
string payeeCashAccount = "";
string expenseAccount = "";
string offsetAccount = "";
string type = "";
long reqID = 0;
foreach (GlAccountSetRequestViewModel glr in req)
{
type = glr.Type;
expenseMain = glr.ExpenseAccount;
payorID = glr.PayorCorpID;
payeeID = glr.PayeeCorpID;
reqID = glr.ReqID;
//...skipping calculation code that works
accountSet.ExpenseAccount = expenseAccount;
accountSet.PayorCashAccount = payorCashAccount;
accountSet.PayeeCashAccount = payeeCashAccount;
accountSet.OffsetAccount = offsetAccount;
accountSet.ReqID = reqID;
result.GlAccountSetViewModels.Add(accountSet);
}
return result;
}
}
}
using FS.Common;
using System.Collections.Generic;
namespace FS.ViewModels.APVendor
{
public class GlAccountSetResponseViewModel : FSObject<GlAccountSetResponseViewModel>
{
public IList<GlAccountSetViewModel> GlAccountSetViewModels { get; set; }
public SuccessErrorWarningResult SuccessErrorWarningResult { get; set; }
}
}
namespace FS.ViewModels.APVendor
{
public class GlAccountSetViewModel
{
public string ExpenseAccount { get; set; }
public string PayorCashAccount { get; set; }
public string PayeeCashAccount { get; set; }
public string OffsetAccount { get; set; }
public long ReqID { get; set; }
}
}
You're adding the same accountSet instance to the list multiple times, only modifying it in the loop. Thus all references to it in the list will "have" the most recently set values.
You need to create a new GlAccountSetViewModel instance in the loop and add that one, or make it a struct to copy it when being added.
I want to check each page values from the API and against the values to change the color of the map marker.
This is my API: http://194.141.118.43:3001/?id=0 where id is from 0 to 16
I want:
if from ?id=0 AL = 1 the marker should be green
if from ?id=0 AL = 2 the marker should be yellow
if from ?id=0 AL = 3 the marker should be orange
if from ?id=0 AL = 4 the marker should be red
So I want to check for all 17 stations (from ?id=0 to ?id=16)
I am currently checking the property Alertlevelwebsite in this method with this API: http://194.141.118.43:3001/stations, But now I have to check all the values from this address for each pin and I have to put a color for the largest value for each pin.
http://194.141.118.43:3001/?id=0 (from 0 to 16)
I use this example from xamarin.forms.maps - https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/workingwithmaps/ and in CustomMapRenderer class I try to change the colors in this method:
protected override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
MKAnnotationView annotationView = null;
if (annotation is MKUserLocation)
return null;
var customPin = GetCustomPin(annotation as MKPointAnnotation);
//Get Value
c_annotation = annotation;
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
annotationView = mapView.DequeueReusableAnnotation(customPin.Name);
if (annotationView == null)
{
annotationView = new CustomMKAnnotationView(annotation, customPin.Name);
annotationView.CalloutOffset = new CGPoint(0, 0);
((CustomMKAnnotationView)annotationView).Name = customPin.Name;
((CustomMKAnnotationView)annotationView).Url = customPin.Url;
((CustomMKAnnotationView)annotationView).Address = customPin.Address;
//Add First Line
((CustomMKAnnotationView)annotationView).AlertLevel = customPin.AlertLevel;
if (customPin.AlertLevel == 1)
{
annotationView.Image = UIImage.FromFile("green.png");
}
else if (customPin.AlertLevel == 2)
{
annotationView.Image = UIImage.FromFile("yellow.png");
}
else if (customPin.AlertLevel == 3)
{
annotationView.Image = UIImage.FromFile("orange.png");
}
else if (customPin.AlertLevel == 4)
{
annotationView.Image = UIImage.FromFile("red.png");
}
//Add Second Line
((CustomMKAnnotationView)annotationView).CodeNum = customPin.CodeNum;
((CustomMKAnnotationView)annotationView).MapCode = customPin.MapCode;
//Here I add the RequestUri for stations
string GenerateRequestUriStations(string endpoint)
{
string requestUri = endpoint;
requestUri += $"stations";
return requestUri;
}
//Here I need the loop from 0 to 16 every page and change the pin icons like above if statement
string GenerateRequestUri(string endpoint)
{
string requestUri = endpoint;
requestUri += $"?id=0";
return requestUri;
}
//This is the value who I need to compare result.WaterData.Ardaforecast but does not allow me to write result.WaterData.Ardaforecast and does not allow me to foreach here .. I don't know why ?
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
}
annotationView.CanShowCallout = true;
configureDetailView(annotationView);
return annotationView;
}
In the comments above the code I mean that when I write:
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
foreach (var item in IAsyncResult)
{
}
When I try to write result. automatic puts me IAsyncResult.. I don't know why.. ?
Can I get an example of how to loop all the pages and change colors on the markers ?
My GetDataFromAPI look like this:
public IEnumerable<AlertLevel> GetDataFromAPI(int mapCode)
{
var listAlert = new List<AlertLevel>();
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint, mapCode));
foreach (var item in reusult.WaterData.Ardaforecast[0].Items)
{
var currentData = new AlertLevel()
{
dateForecast = item.DateTimeForecast,
levelForecast = item.AlertLevelForecast
};
listAlert.Add(currentData);
}
return listAlert;
}
My GetWaterDataForecast look like this:
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using MaritsaTundzhaForecast.Models;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast.Services
{
public class RestServiceData
{
HttpClient _client1;
HttpClient _client2;
public RestServiceData()
{
_client1 = new HttpClient();
_client2 = new HttpClient();
}
public WaterBindingData GetWaterDataForecast(string query, string query2)
{
WaterDataJson waterData = new WaterDataJson();
WaterStationsJson waterStations = new WaterStationsJson();
WaterBindingData result = new WaterBindingData();
try
{
var task = Task.Run(() => _client1.GetAsync(query));
task.Wait();
var response = task.Result;
var task2 = Task.Run(() => _client2.GetAsync(query2));
task2.Wait();
var response2 = task2.Result;
if (response.IsSuccessStatusCode && response2.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync().Result;
var content2 = response2.Content.ReadAsStringAsync().Result;
var json = content2.Replace("\"ardaforecast\":[[", "\"ardaforecast\":[ {\"items\": [")
.Replace("}],{\"fieldCount\"", "}],\"details\":{\"fieldCount\"")
.Replace("}]}", "}}]}");
waterData = JsonConvert.DeserializeObject<WaterDataJson>(json);
waterStations = JsonConvert.DeserializeObject<WaterStationsJson>(content);
result.WaterData = waterData;
result.WaterStation = waterStations;
}
}
catch (Exception ex)
{
Debug.WriteLine("\t\tERROR {0}", ex.Message);
}
return result;
}
}
}
My WaterBindingData look like:
using System;
namespace MaritsaTundzhaForecast.Models
{
public class WaterBindingData
{
public WaterDataJson WaterData { get; set; }
public WaterStationsJson WaterStation { get; set; }
}
}
My WaterDataJson and WaterStations look like:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast
{
public class WaterDataJson
{
public List<ForecastBody> Ardaforecast { get; set; }
}
public class ForecastBody
{
public ForecastItem[] Items { get; set; }
public ForecastDetails Details { get; set; }
}
public class ForecastItem
{
[JsonProperty("Dt")]
public DateTime DateTimeForecast { get; set; }
[JsonProperty("AL")]
public int AlertLevelForecast { get; set; }
}
public class ForecastDetails
{
public int fieldCount { get; set; }
public int affectedRows { get; set; }
public int insertId { get; set; }
public int serverStatus { get; set; }
public int warningCount { get; set; }
public int changedRows { get; set; }
public string message { get; set; }
public bool protocol41 { get; set; }
}
}
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast.Models
{
public class WaterStationsJson
{
public List<ForecastStations> Stations { get; set; }
}
public class ForecastStations
{
[JsonProperty("Map_code")]
public int MapCode { get; set; }
[JsonProperty("NAME_IME")]
public string NameEN { get; set; }
[JsonProperty("NAME_CYR")]
public string NameBG { get; set; }
[JsonProperty("Alertlevelwebsite")]
public int AlertLevelStation { get; set; }
[JsonProperty("CODENUM")]
public int CodeNum { get; set; }
}
}
I have the following class, which has Fixture as the parent class -> FixtureSensors etc are child classes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FixtureData
{
class Fixture
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public List<FixtureSensors> Sensors = new List<FixtureSensors>();
public List<FixturePneumaticValves> Valves { get; set; }
}
class FixturePneumaticValves
{
public int Id { get; set; }
public string Hardware { get; set; }
public string Connection { get; set; }
public string Type { get; set; }
public List<FixturePneumaticUnits> Units { get; set; }
}
class FixtureSensors
{
public string Fixture { get; set; }
public string Hardware { get; set; }
public string Connection { get; set; }
public string Unit { get; set; }
}
class FixturePneumaticUnits
{
public string Fixture { get; set; }
public string Hardware { get; set; }
public string Connection { get; set; }
}
}
I would like to display information from the different classes on a datagridview which is editable. I managed to display this information, however to make the datagridview editable I had to include a class after the linq select new statement:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FixtureData;
namespace GridViewObjects_DB
{
public partial class Form1 : Form
{
private BindingSource source = new BindingSource();
static List<Fixture> Fixtures = new List<Fixture>()
{
new Fixture() { Id = 0, Name = "S7K010LFX1", Type = "GEO WELDING",Sensors = new List<FixtureSensors>()
{
new FixtureSensors(){Connection = "0.0", Hardware = "S7K010LFX1VS1",Unit = "102L-C1"},
new FixtureSensors(){Connection = "0.1", Hardware = "S7K010LFX1VS1",Unit = "103L-C1"},
new FixtureSensors(){Connection = "0.2", Hardware = "S7K010LFX1VS1",Unit = "103L-C1"},
new FixtureSensors(){Connection = "0.3", Hardware = "S7K010LFX1VS1",Unit = "104L-C1"},
new FixtureSensors(){Connection = "0.4", Hardware = "S7K010LFX1VS1",Unit = "105L-C1"}
},Valves = new List<FixturePneumaticValves>()
{
new FixturePneumaticValves(){Id=0,Connection = "0.0",Hardware = "S7K010LFX1VS1",Type = "Clp",Units = new List<FixturePneumaticUnits>()
{
new FixturePneumaticUnits(){Hardware = "S7K010LFX1VS1",Connection = "0.6"},
new FixturePneumaticUnits(){Hardware = "S7K010LFX1VS1",Connection = "1.0"},
new FixturePneumaticUnits(){Hardware = "S7K010LFX1VS1",Connection = "1.2"},
new FixturePneumaticUnits(){Hardware = "S7K010LFX1VS1",Connection = "1.4"},
new FixturePneumaticUnits(){Hardware = "S7K010LFX1VS1",Connection = "1.6"}
}
}
}
}
};
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
source.DataSource =(from fixture in Fixtures
from sensors in fixture.Sensors
select new Fixture() {Name = sensors.Fixture}
);
dataGridView1.DataSource = source;
dataGridView1.ReadOnly = false;
dataGridView1.Enabled = true;
}
}
}
This limits me to only display properties of the Fixture class and I would like to know of a way around this.
I am having the following criteria:-
1.Create gmail group using query execution in sql db. This query will filter contacts on the basis of region.
2.These contacts may or may not be different for each send request. It depends upon the users those who are active at the time of send.
3.I am able to send mail to group.
Main problem is related with how i can update group each time before sending mail to group members excluding inactive members.
Please let me know if you need more explanation.I will try my best.
UPDATE:
I had done the following code from a Console application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Contacts;
using Google.GData.Contacts;
using Google.GData.Client;
using Google.GData.Extensions;
namespace IMAPCommands
{
class Program
{
static void Main(string[] args)
{ GoogleContactService.InitializeService("mailid", "password");
List<ContactDetail> test = GoogleContactService.GetContacts("System Group: My Contacts");
//Use break point here
Console.ReadLine();
}
public class GoogleContactService
{
#region Properties
public static ContactsService GContactService = null;
#endregion
#region Methods
public static void InitializeService(string username, string password)
{
GContactService = new ContactsService("Contact Infomation");
GContactService.setUserCredentials(username, password);
}
public static List<ContactDetail> GetContacts(string GroupName = null)
{
List<ContactDetail> contactDetails = new List<ContactDetail>();
ContactsQuery contactQuery = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
contactQuery.NumberToRetrieve = 1000;
if (!String.IsNullOrEmpty(GroupName))
{
GroupEntry ge = GetGroup(GroupName);
if (ge != null)
contactQuery.Group = ge.Id.AbsoluteUri;
}
else
{
string groupName = "";
GroupEntry ge = GetGroup(groupName);
if (ge != null)
contactQuery.Group = ge.Id.AbsoluteUri;
}
ContactsFeed feed = GContactService.Query(contactQuery);
foreach (ContactEntry entry in feed.Entries)
{
if (entry.Title.Text == "TechnicalBulletinName")
{
int test = entry.Emails.Count;
ContactDetail contact = new ContactDetail
{
Name = entry.Title.Text,
EmailAddress1 = entry.Emails.Count >= 1 ? entry.Emails[0].Address : "",
EmailAddress2 = entry.Emails.Count >= 2 ? entry.Emails[1].Address : "",
Phone1 = entry.Phonenumbers.Count >= 1 ? entry.Phonenumbers[0].Value : "",
Phone2 = entry.Phonenumbers.Count >= 2 ? entry.Phonenumbers[1].Value : "",
Address = entry.PostalAddresses.Count >= 1 ? entry.PostalAddresses[0].FormattedAddress : "",
Details = entry.Content.Content
};
contact.UserDefinedFields = new List<UDT>();
foreach (var udt in entry.UserDefinedFields)
{
contact.UserDefinedFields.Add(new UDT { Key = udt.Key, Value = udt.Value });
}
contactDetails.Add(contact);
}
}
return contactDetails;
}
#endregion
#region Helpers
public static GroupEntry GetGroup(string GroupName)
{
GroupEntry groupEntry = null;
GroupsQuery groupQuery = new GroupsQuery(GroupsQuery.CreateGroupsUri("default"));
groupQuery.NumberToRetrieve = 100;
GroupsFeed groupFeed = GContactService.Query(groupQuery);
foreach (GroupEntry entry in groupFeed.Entries)
{
if (entry.Title.Text.Equals(GroupName, StringComparison.CurrentCultureIgnoreCase))
{
groupEntry = entry;
break;
}
}
return groupEntry;
}
#endregion
}
public class ContactDetail
{
public string Name { get; set; }
public string EmailAddress1 { get; set; }
public string EmailAddress2 { get; set; }
public string Phone1 { get; set; }
public string Phone2 { get; set; }
public string Address { get; set; }
public string Details { get; set; }
public string Pipe { get; set; }
public string Relationship { get; set; }
public string Status { get; set; }
public List<UDT> UserDefinedFields { get; set; }
}
public class UDT
{
public string Key { get; set; }
public string Value { get; set; }
}
}
Still not able to get list of contacts which are member of group TechnicalBulletinName. I am only able to get emailID of this group not members of the group.
I am trying to show out History for my windows 8 application which includes date, time , Floor ,Zone , Longitutde and latitude. I tried the code below but there was no output in it above.
THe image you can see on the link down below that I want to show on my application.But I can see nothing when I run my program.
I have three classes for using linq to sql to retrieve database and show information through it.The main class is History.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Text;
using System.Data.Linq;
namespace SmartParking
{
public partial class History : PhoneApplicationPage
{
private readonly HistoryDataContext historylog;
public History()
{
InitializeComponent();
// createDB();
}
public HistoryDataContext Log
{
get { return historylog; }
}
public void createDB()
{
using (HistoryDataContext historylog = new HistoryDataContext(HistoryDataContext.DBConnectionString))
{
if (historylog.DatabaseExists() == false)
{
historylog.CreateDatabase();
addDataDB();
}
}
}
public void addDataDB()
{
using (HistoryDataContext historylog = new HistoryDataContext(HistoryDataContext.DBConnectionString))
{
HistoryDB hdb = new HistoryDB
{
// Date = DateTime.Today,
// Time = DateTime.Now.TimeOfDay,
Zone = Checkin.Zone_st,
Floor = Checkin.Floor_st,
location_latitude = Checkin.Latitud_do,
location_longtitud = Checkin.Longtitude_do
};
historylog.history.InsertOnSubmit(hdb);
historylog.SubmitChanges();
GetHistoryLog();
}
}
public IList<HistoryDB> GetHistoryLog()
{
IList<HistoryDB> HistoryList = null;
using (HistoryDataContext historylog = new HistoryDataContext(HistoryDataContext.DBConnectionString))
{
IQueryable<HistoryDB> query = from histoy in historylog.history select histoy;
HistoryList = query.ToList();
}
return HistoryList ;
}
}
}
The next class is HistoryDB.cs with the tables and columns
[Table]
public class HistoryDB
{
[Column(CanBeNull = false)]
public DateTime Date
{ get; set; }
[Column(CanBeNull = false)]
public TimeSpan Time
{ get; set; }
[Column(CanBeNull = false)]
public String Zone
{ get; set; }
[Column(CanBeNull = false)]
public String Floor
{ get; set; }
[Column(CanBeNull = false)]
public double location_latitude
{ get; set; }
[Column(CanBeNull = false)]
public double location_longtitud
{ get; set; }
}
The next class is HistoryDataContext.cs.
public class HistoryDataContext:DataContext
{
public static string DBConnectionString = "Data Source=isostore:/History.sdf";
public HistoryDataContext(string DBConnectionString)
: base(DBConnectionString)
{
}
public Table<HistoryDB> history
{
get
{
return this.GetTable<HistoryDB>();
}
}
}
What I am trying is to get information from the NFC tag and store it in the local database and then retrieve it in the history page. The code below is to read from nfc tag but I dunno how again to save in the local databse from there and retrive it back in the history page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Networking.Proximity;
using NdefLibrary.Ndef;
using NdefLibraryWp.Ndef;
using Windows.Networking.Sockets; // needed for DataReader, DataWriter
using Windows.UI.Popups;
using Microsoft.Phone.UserData;
using System.Text;
using Windows.Phone.PersonalInformation;
using SmartParking.Resources;
using System.Diagnostics;
namespace SmartParking
{
public partial class Checkin : PhoneApplicationPage
{
private ProximityDevice _device;
private long _subscriptionIdNdef;
public static double Latitud_do { get; set; }
public static double Longtitude_do { get; set; }
public static string Floor_st { get; set; }
public static string Zone_st { get; set; }
History store = new History();
public Checkin()
{
InitializeProximityDevice();
InitializeComponent();
}
private void SetLogStatus(string newStatus)
{
Dispatcher.BeginInvoke(() => { if (LogStatus != null) LogStatus.Text = newStatus; });
}
private void SetFloorStatus(string newStatus)
{
Dispatcher.BeginInvoke(() => { if (FloorStatus != null) FloorStatus.Text = newStatus; });
}
private void ApplicationBarIconButton_Click(object sender, System.EventArgs e)
{
MessageBox.Show(" ");
}
private void InitializeProximityDevice()
{
_device = Windows.Networking.Proximity.ProximityDevice.GetDefault();
if (_device != null)
{
_subscriptionIdNdef = _device.SubscribeForMessage("NDEF", MessageReceivedHandler);
}
}
private void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message)
{
var rawMsg = message.Data.ToArray();
var ndefMessage = NdefMessage.FromByteArray(rawMsg);
////// Loop over all records contained in the NDEF message
foreach (NdefRecord record in ndefMessage)
{
if (NdefTextRecord.IsRecordType(record))
{
// Convert and extract URI info
var textRecord = new NdefTextRecord(record);
//var str = textRecord.Text;
string[] str = textRecord.Text.Split('|');
var latitude = str[2];
Latitud_do = double.Parse(latitude);
var longtitude = str[3];
Longtitude_do = double.Parse(longtitude);
var Floor_st = str[0];
var Zone_st = str[1];
SetLogStatus("Floor: " + Floor_st + " Zone: " + Zone_st );
SetFloorStatus("Longitude: " + latitude + " Longitude: " + longtitude);
store.addDataDB();
}
}
}
}
}
The Image of the table is in the link below
https://www.dropbox.com/s/g87yta6hegjstge/Untitled.png?dl=0
try this:
In Database There Should be a Primary key otherwise it would Throw an Exception and the Datatype that is TimeSpan not supported so you need to take DateTime or String as Done Below :
[Table]
public class HistoryDB
{
[Column(IsPrimaryKey = true)]
public int Id { get; set; }
[Column(CanBeNull = false)]
public DateTime Date
{ get; set; }
[Column(CanBeNull = false)]
public DateTime Time
{ get; set; }
[Column(CanBeNull = false)]
public String Zone
{ get; set; }
[Column(CanBeNull = false)]
public String Floor
{ get; set; }
[Column(CanBeNull = false)]
public double location_latitude
{ get; set; }
[Column(CanBeNull = false)]
public double location_longtitud
{ get; set; }
}
public void addDataDB()
{
using (HistoryDataContext historylog = new HistoryDataContext(HistoryDataContext.DBConnectionString))
{
HistoryDB hdb = new HistoryDB
{
Id = 0,
Date = DateTime.Today,
Time = DateTime.Now,
Zone = "Zone",
Floor = "Floore",
location_latitude = 00.00,
location_longtitud = 00.00
};
historylog.history.InsertOnSubmit(hdb);
historylog.SubmitChanges();
GetHistoryLog();
}
}
I have implemented above thing and its working Properly