I've implemented what I think is a pretty vanilla usage of Realm:
public class MyObj : RealmObject
{
[PrimaryKey]
public string Key { get; set; }
public bool Value { get; set; }
}
then, in my app:
using(Realm r = Realm.GetInstance()) {
var c1 = r.All<MyObj>().Count();
}
which returns zero, as expected.
Then I add an object:
using(Realm r = Realm.GetInstance()) {
r.Write(() =>
{
var obj = new MyObj() { Key = "test", Value = true };
r.Add(obj);
});
}
then reopen it and get the count:
using(r = Realm.GetInstance()) {
var c2 = r.All<MyObj>().Count();
}
and c2 is one, as expected. So far, so good.
But when I close my app, and restart, c1 (the initial count) is zero, not one.
Any idea why?
Sorry,we couldn't see the other code of your app.
But you can refer to an article by entering key words Xamarin.Forms - Working With Realm Database in your browser. It works properly even after restarting the app.
You can also check the full sample here.
The main code is:
public partial class MainPage : ContentPage
{
List<OptionItems> optionItems = new List<OptionItems>();
Student editStudent;
public MainPage()
{
InitializeComponent();
imgBanner.Source = ImageSource.FromResource("XamarinFormsRelam.images.banner.png");
var realmDB = Realm.GetInstance();
List<Student> studentList = realmDB.All<Student>().ToList();
listStudent.ItemsSource=studentList;
}
private void btnAdd_Clicked(object sender, EventArgs e)
{
var realmDB = Realm.GetInstance();
var students= realmDB.All<Student>().ToList();
var maxStudentId = 0;
if (students.Count!=0)
maxStudentId = students.Max(s=>s.StudentID);
Student student = new Student()
{
StudentID = maxStudentId + 1,
StudentName = txtStudentName.Text
};
realmDB.Write(() =>
{
realmDB.Add(student);
});
txtStudentName.Text = string.Empty;
List<Student> studentList = realmDB.All<Student>().ToList();
listStudent.ItemsSource = studentList;
}
private async void listOptions_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var realmDB = Realm.GetInstance();
OptionItems selectedItem = optionList.SelectedItem as OptionItems;
if (selectedItem != null)
{
switch (selectedItem.OptionText)
{
case "Edit":
popupOptionView.IsVisible = false;
popupEditView.IsVisible = true;
editStudent = realmDB.All<Student>().First(b => b.StudentID == selectedItem.StudentId);
txtEditStudentName.Text = editStudent.StudentName;
break;
case "Delete":
var removeStudent = realmDB.All<Student>().First(b => b.StudentID == selectedItem.StudentId);
using (var db = realmDB.BeginWrite())
{
realmDB.Remove(removeStudent);
db.Commit();
}
await DisplayAlert("Success", "Student Deleted", "OK");
popupOptionView.IsVisible = false;
List<Student> studentList = realmDB.All<Student>().ToList();
listStudent.ItemsSource = studentList;
break;
default:
popupOptionView.IsVisible = false;
break;
}
optionList.SelectedItem = null;
}
}
protected override void OnAppearing()
{
base.OnAppearing();
var realmDb = Realm.GetInstance();
}
private void listStudent_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
Student selectedStudent = listStudent.SelectedItem as Student;
if(selectedStudent!=null)
{
optionItems.Add(new OptionItems { OptionText = "Edit",StudentId=selectedStudent.StudentID});
optionItems.Add(new OptionItems { OptionText = "Delete", StudentId = selectedStudent.StudentID });
optionItems.Add(new OptionItems { OptionText = "Cancel"});
optionList.ItemsSource = optionItems;
popupOptionView.IsVisible = true;
}
}
private void Button_Clicked(object sender, EventArgs e)
{
popupEditView.IsVisible = false;
}
private async void Button_Clicked_1(object sender, EventArgs e)
{
var realmDB = Realm.GetInstance();
var selectedStudent = realmDB.All<Student>().First(b => b.StudentID == editStudent.StudentID);
using (var db = realmDB.BeginWrite())
{
editStudent.StudentName = txtEditStudentName.Text;
db.Commit();
}
await DisplayAlert("Success", "Student Updated","OK");
txtEditStudentName.Text = string.Empty;
popupEditView.IsVisible = false;
}
}
Are you deploying on a physical device? If that's the case, it's likely due to the automatic backup and restore functionality built into Android - when you deploy the app, it treats it as an install and restores the last known state.
You can read about it here: An Android app remembers its data after uninstall and reinstall but the tl;dr is - go to settings and turn off "Automatic Restore" or update your manifest to instruct Android not to backup the data.
Related
I have a controller that calls an api to get a list of Positions and Employees . First it puts the api results into a model class - IDMSElements (1). Then the controller takes the IDMSElements object and converts it to a PositionSlots object (2). Then the PositionSlots object needs to be updated with additional data from a database (3). So in simplified version of my controller I have:
(1) IDMSElements elements = getslots.CopyDocToElements(doc);
(2) PositionSlots myslots = (PositionSlots)elements;
(3) myslots.UpdateDetails(db);
I am concerned about the myslots.UpdateDetails(db) because additional code in the controller depends on UpdateDetails having been run. I would like the UpdateDetails to be run by default when creating the PositionSlots object. But I think multiple database calls in a constructor probably should not be done. How can I make it so the UpdateDetails is automatically invoked after the PositionSlots object is instantiated?
Thank you very much!
Controller:
[Authorize]
public class PSListController : Controller
{
private static readonly log4net.ILog _logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private PositionControlContext db = new PositionControlContext();
private GetPositionSlots getslots = new GetPositionSlots();
...
public async Task<ActionResult> ByCostCenter(int costCenter)
{
string ssapiuri = getslots.BuildAPIuri($"/current/?UDAKunit={costCenter.ToString()}");
_logger.Debug($"{ssapiuri.ToString()}");
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
HttpResponseMessage result = await getslots.GetDataFromIDMSapi(ssapiuri);
stopWatch.Stop();
_logger.Debug($"Response received. Milliseconds elapsed: {stopWatch.Elapsed.TotalMilliseconds.ToString()}");
if (result.StatusCode != HttpStatusCode.OK)
{
_logger.Debug("Error retrieving data from API. Milliseconds elapsed: " + stopWatch.Elapsed.TotalMilliseconds.ToString());
throw new HttpException(404, "NotFound");
}
stopWatch.Restart();
XDocument doc = XDocument.Load(result.Content.ReadAsStreamAsync().Result);
stopWatch.Stop();
_logger.Debug($"API result loaded into XDocument. Milliseconds elapsed: {stopWatch.Elapsed.TotalMilliseconds.ToString()}\n");
_logger.Debug(doc.ToString());
IDMSElements elements = getslots.CopyDocToElements(doc);
XMLDocStats docstats = new XMLDocStats(elements);
_logger.Debug(docstats.ToString());
PositionSlots myslots = (PositionSlots)elements;
myslots.UpdateDetails(db);
//because this is dependent upon UpdatePositionSlotId having been run
//need to find a way to force UpdateDetails to run other than calling from Controller??
var mainPositionSlots = myslots.PositionsCurrentAndActive;
var budget = db.Database.SqlQuery<Budget>("GetBudgetForCostCenter #costCenter = {0}", costCenter);
List<Budget> budgetRows = budget.ToList();
JobClassGroups jobClassGroups = new JobClassGroups(mainPositionSlots, budgetRows);
Department dept = db.Departments.AsNoTracking().Where(d => d.CostCenter == costCenter).SingleOrDefault();
var model = new ByCostCenter_vm(dept, myslots, jobClassGroups);
ViewBag.stats = docstats.ToString();
return View("ByCostCenter", model);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
IDMSElements Class:
public class IDMSElements
{
//properties
public ICollection<IDMSElementData> Elements { get; set; }
//constructors
public IDMSElements() { }
public IDMSElements(ICollection<IDMSElementData> elList)
{
Elements = elList;
}
//methods
public static explicit operator PositionSlots(IDMSElements obj)
{
//this is assuming we are looking at a list of elements
//that contains the "current" positions
Dictionary<string, PositionSlotDetail> positionSlots = new Dictionary<string, PositionSlotDetail>();
var sorted = from element in obj.Elements
orderby element.positionNbr
select element;
foreach (IDMSElementData el in sorted)
{
if (!positionSlots.ContainsKey(el.positionNbr))
{
PositionSlotDetail psd = new PositionSlotDetail
{
CostCenter = Int32.Parse(el.UDAKunit),
CostCenter_7Char = el.UDAKunit,
PositionNumber = el.positionNbr,
PositionSlotId = 0,
JobClassId = el.jobClassCode.Replace("-", ""),
JobClassFullDisplayCd = string.Empty,
JobTitle = string.Empty,
SalaryGradeCd = string.Empty,
FTE_percent = el.FTEpercent / 100,
EmployeeId = el.employeeID,
EmployeeName = String.Empty,
PositionEffDate = el.positionEffDate,
PositionEffDateNext = el.positionEffDateNext,
PositionBeginDate = el.positionBeginDate,
PositionEndDate = el.positionEndDate,
DirectLeaderID = string.Empty,
DirectLeaderName = string.Empty,
DirectLeaderNetID = string.Empty,
FLSAstatusCode = el.FLSAstatusCode,
FLSAstatusDesc = el.FLSAstatusDesc,
EmploymentTypeCode = el.employmentTypeCode,
EmploymentTypeDesc = el.employmentTypeDesc,
IsOverloaded = false,
};
positionSlots[el.positionNbr] = psd;
}
Assignment newAssignment = new Assignment
{
PvID = el.employeeID,
AssignBeginDate = el.assignBeginDate,
AssignEndDate = el.assignEndDate,
AssignEffDate = el.assignEffDate,
AssignEffDateNext = el.assignEffDateNext,
};
PositionSlotDetail thePSD = positionSlots[el.positionNbr];
thePSD.Assignments.Add(newAssignment);
if (thePSD.Assignments.Any(assignment => Regex.IsMatch(assignment.PvID, #"^\d+$")))
{
thePSD.Status = "FILLED";
if (thePSD.Assignments.Where(assignment => Regex.IsMatch(assignment.PvID, #"^\d+$")).Count() > 1)
{
thePSD.IsOverloaded = true;
}
}
else
{
thePSD.Status = "VACANT";
}
}
var output = new PositionSlots(positionSlots.Values.ToList());
return output;
}
...
}
PositionSlots class:
public class PositionSlots
{
//Constructor
public PositionSlots(ICollection<PositionSlotDetail> pslist)
{
Positions = pslist;
}
//properites
public ICollection<PositionSlotDetail> Positions { get; }
private bool DetailsUpdated { get; set; } = false;
public IEnumerable<PositionSlotDetail> PositionsCurrentAndActive
{
get
{
return from position in Positions
where position.PositionSlotId > 0 && position.PositionEndDate >= DateTime.Today
select position;
}
}
public IEnumerable<PositionSlotDetail> PositionsNotFoundInPositionControl
{
get
{
return from position in Positions
where position.PositionSlotId == 0
select position;
}
}
public IEnumerable<PositionSlotDetail> PositionsClosed
{
get
{
return from psd in Positions
where psd.PositionEndDate < DateTime.Today
&& psd.PositionSlotId > 0
select psd;
}
}
public decimal ActualFTETotal
{
get
{
return (from position in PositionsCurrentAndActive
from assignment in position.Assignments
where position.Assignments.Count() >= 1 && (!assignment.PvID.Equals("VACANT"))
select position.FTE_percent).Sum();
}
}
public int FilledTotal
{
get
{
return PositionsCurrentAndActive.Where(x => x.Status == "FILLED").Count();
}
}
public int VacantTotal
{
get
{
return PositionsCurrentAndActive.Where(x => x.Status == "VACANT").Count();
}
}
public int OverloadedTotal
{
get
{
return PositionsCurrentAndActive.Where(x => x.IsOverloaded).Count();
}
}
//methods
public void UpdateDetails(PositionControlContext db)
{
if (!DetailsUpdated)
{
UpdateJobClassificationInfo(db);
UpdateEmployeeName(db);
UpdatePositionSlotId(db); //if not found, PositionSlotId = 0
//UpdateIsBudgeted(db);
UpdateDirectLeader(db);
DetailsUpdated = true;
}
else
{
return;
}
}
private void UpdateJobClassificationInfo(PositionControlContext db)
{
string[] jobClassIds = (from x in Positions select x.JobClassId).Distinct().ToArray();
var JobClassList = (from jc in db.JobClassifications where jobClassIds.Contains(jc.JobClassId) select jc).ToDictionary(jc => jc.JobClassId, jc => jc, StringComparer.OrdinalIgnoreCase);
foreach (PositionSlotDetail psd in Positions)
{
if (!string.IsNullOrWhiteSpace(psd.JobClassId) && !psd.JobClassId.Equals("MISSING"))
{
JobClassification jobClassification;
if (JobClassList.TryGetValue(psd.JobClassId, out jobClassification))
{
psd.JobClassFullDisplayCd = jobClassification.JobClassFullDisplayCd;
psd.JobTitle = jobClassification.JobTitle;
psd.SalaryGradeCd = jobClassification.SalaryGradeCd;
}
else
{
psd.JobClassFullDisplayCd = ($"{psd.JobClassId} not found in view V_JobClassifications.");
psd.JobTitle = ($"{psd.JobClassId} not found in view V_JobClassifications.");
psd.SalaryGradeCd = "--";
}
}
else
{
psd.JobClassFullDisplayCd = "MISSING";
psd.JobTitle = "MISSING";
}
}
return;
}
private void UpdateEmployeeName(PositionControlContext db)
{
string[] empIdsStr = (from position in Positions
from assignment in position.Assignments
where (!assignment.PvID.Equals("VACANT"))
select assignment.PvID).Distinct().ToArray();
// Positions.SelectMany(x => x.Assignments).SelectMany(x => x.PvID).ToArray();
//string[] empIdsStr = (from x in Positions where (!x.EmployeeId.Contains("VACANT")) select x.EmployeeId).Distinct().ToArray();
//int[] empIdsInt = Array.ConvertAll(empIdsStr, int.Parse);
var EmployeeList = (from emp in db.IdAM_personLU where empIdsStr.Contains(emp.pvID) select emp).ToDictionary(emp => emp.pvID,
emp => emp.EmployeeFullName, StringComparer.OrdinalIgnoreCase);
EmployeeList["VACANT"] = "VACANT";
foreach (PositionSlotDetail psd in Positions)
{
string empName;
if (EmployeeList.TryGetValue(psd.EmployeeId, out empName))
{
psd.EmployeeName = empName;
}
else
{
psd.EmployeeName = ($"{psd.EmployeeId} not found in Employee table.");
}
foreach (Assignment emp in psd.Assignments)
{
string empName2;
if (EmployeeList.TryGetValue(emp.PvID, out empName2))
{
emp.EmpDisplayName = empName2;
}
else
{
emp.EmpDisplayName = ($"{psd.EmployeeId} not found in Employee table.");
}
}
}
return;
}
private void UpdateDirectLeader(PositionControlContext db)
{
string[] empIdsStr = (from x in Positions where (!x.EmployeeId.Contains("VACANT")) select x.EmployeeId).Distinct().ToArray();
//int[] empIdsInt = Array.ConvertAll(empIdsStr, int.Parse);
Dictionary<string, IdAM_arborLU> DirectLeader = new Dictionary<string, IdAM_arborLU>();
var EmployeeDirectLeaderList = (from emp in db.IdAM_arborLU where empIdsStr.Contains(emp.emp_pvID) select emp).ToDictionary(emp => emp.emp_pvID,
emp => emp, StringComparer.OrdinalIgnoreCase);
foreach (PositionSlotDetail psd in Positions)
{
if (psd.EmployeeId != "VACANT") //will just leave DirectLeaderId and DirectLeaderName as string.Empty
{
IdAM_arborLU supervisor;
if (EmployeeDirectLeaderList.TryGetValue(psd.EmployeeId, out supervisor))
{
psd.DirectLeaderName = supervisor.sup_name;
psd.DirectLeaderID = supervisor.sup_pvID;
psd.DirectLeaderNetID = supervisor.sup_netID;
}
else
{
psd.DirectLeaderName = ($"{psd.EmployeeId} not found in Arbor table.");
}
}
foreach (Assignment emp in psd.Assignments)
{
if (psd.EmployeeId != "VACANT")
{
IdAM_arborLU supervisor2;
if (EmployeeDirectLeaderList.TryGetValue(psd.EmployeeId, out supervisor2))
{
emp.DirectLeaderName = supervisor2.sup_name;
emp.DirectLeaderID = supervisor2.sup_pvID;
emp.DirectLeaderNetID = supervisor2.sup_netID;
}
else
{
emp.DirectLeaderName = ($"{psd.EmployeeId} not found in Arbor table.");
emp.DirectLeaderID = "--";
emp.DirectLeaderNetID = "--";
}
}
}
}
return;
}
private void UpdatePositionSlotId(PositionControlContext db)
{
string[] posnumber = (from x in Positions
select x.PositionNumber).ToArray();
var slots = (from ps1 in db.PositionSlots
where posnumber.Contains(ps1.PositionNumber)
select ps1).ToDictionary(ps => ps.PositionNumber.Trim(), ps => ps.PositionSlotId, StringComparer.OrdinalIgnoreCase);
foreach (PositionSlotDetail psd in Positions)
{
int posSlotId = 0;
if (slots.TryGetValue(psd.PositionNumber, out posSlotId))
{
psd.PositionSlotId = posSlotId;
}
}
return;
}
private void UpdateIsBudgeted(PositionControlContext db)
{
string[] posnumber = (from x in Positions
select x.PositionNumber).ToArray();
var slots = (from ps1 in db.PositionSlots
where posnumber.Contains(ps1.PositionNumber)
select ps1).ToDictionary(ps => ps.PositionNumber.Trim(), ps => ps.IsBudgeted, StringComparer.OrdinalIgnoreCase);
foreach (PositionSlotDetail psd in Positions)
{
bool isbudgeted = false;
if (slots.TryGetValue(psd.PositionNumber, out isbudgeted))
{
psd.IsBudgeted = isbudgeted;
}
}
return;
}
}
you can achieve this by writing a method:
IDMSElement.ToPositionSlot(db)
and then use it as follow:
PositionSlots myslots = elements.Select(x => x.ToPositionSlot(db))
I want to declare the following things:
var simlBot = new SimlBot();
var botUser = simlBot.CreateUser();
var packageString = File.ReadAllText("SIMLPackage.simlpk");
simlBot.PackageManager.LoadFromString(packageString);
If I declare it directly in the class I get: "The contextual keyword 'var' may only appear within a local variable declaration or in script code"
I can't declare it inside an if statement because I can't access it from outside.
if (hasBotBeenCreated == false)
{
var simlBot = new SimlBot();
var botUser = simlBot.CreateUser();
var packageString = File.ReadAllText("SIMLPackage.simlpk");
simlBot.PackageManager.LoadFromString(packageString);
}
I need to use the following form inside a function:
var chatRequest = new ChatRequest(textReceived, botUser);
var chatResult = simlBot.Chat(chatRequest);
What can I do? The problem is that the last snippet of code can't access botUser and simlBot. The way I have it working now is recreating the object every time the function is called, but that takes a lot of time.
My complete code is
public partial class Form1 : Form
{
string textEntered = "";
string response = "";
SpeechSynthesizer synth = new SpeechSynthesizer();
bool hasBotBeenCreated = false;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textEntered = textBox1.Text;
textBox1.Text = "";
if (textEntered != "")
{
sendToAI(textEntered);
}
}
void sendToAI(string textReceived)
{
listBox1.Items.Add(textEntered);
response = getResponse(textEntered);
listBox1.Items.Add(response);
synth.Speak(response);
}
string getResponse(string textReceived)
{
if (hasBotBeenCreated == false)
{
var simlBot = new SimlBot();
var botUser = simlBot.CreateUser();
var packageString = File.ReadAllText("SIMLPackage.simlpk");
simlBot.PackageManager.LoadFromString(packageString);
}
var chatRequest = new ChatRequest(textReceived, botUser);//These two can't access the objects created above
var chatResult = simlBot.Chat(chatRequest);
if (chatResult.Success)
{
var botMessage = chatResult.BotMessage;
return botMessage;
}
else
{
return "I don't have a response for that";
}
}
}
Revision 2:
string getResponse(string textReceived)
{
SimlBot simlBot;
BotUser botUser;
if (hasBotBeenCreated == false)
{
simlBot = new SimlBot();
botUser = simlBot.CreateUser();
var packageString = File.ReadAllText("SIMLPackage.simlpk");
simlBot.PackageManager.LoadFromString(packageString);
}
var chatRequest = new ChatRequest(textReceived, botUser); //These get the error
var chatResult = simlBot.Chat(chatRequest);
if (chatResult.Success)
{
var botMessage = chatResult.BotMessage;
return botMessage;
}
else
{
return "I don't have a response for that";
}
}
Add the members:
SimlBot simlBot;
WhatEverTypeOfCreateUserIs botUser;
Then initialize them:
if (hasBotBeenCreated == false)
{
simlBot = new SimlBot();
botUser = simlBot.CreateUser();
....
}
---------- Full Code ----------
public partial class Form1 : Form
{
string textEntered = "";
string response = "";
SpeechSynthesizer synth = new SpeechSynthesizer();
bool hasBotBeenCreated = false;
SimlBot simlBot;
BotUser botUser;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textEntered = textBox1.Text;
textBox1.Text = "";
if (textEntered != "")
{
sendToAI(textEntered);
}
}
void sendToAI(string textReceived)
{
listBox1.Items.Add(textEntered);
response = getResponse(textEntered);
listBox1.Items.Add(response);
synth.Speak(response);
}
string getResponse(string textReceived)
{
if (hasBotBeenCreated == false)
{
simlBot = new SimlBot();
botUser = simlBot.CreateUser();
var packageString = File.ReadAllText("SIMLPackage.simlpk");
simlBot.PackageManager.LoadFromString(packageString);
}
var chatRequest = new ChatRequest(textReceived, botUser);//These two can't access the objects created above
var chatResult = simlBot.Chat(chatRequest);
if (chatResult.Success)
{
var botMessage = chatResult.BotMessage;
return botMessage;
}
else
{
return "I don't have a response for that";
}
}
}
bit of a noob when it comes to async operations but I am having some trouble with a ObservableCollection and not sure if the problem is because it is in an async method or not. When it tries to add the delegate it crashes with a System.AccessViolationException error... Here's the code:
public partial class ContactsList : PhoneApplicationPage
{
static ObservableCollection<Contact> dataSource { get; set; }
public ContactsList()
{
InitializeComponent();
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
dataSource.CollectionChanged += this.dataSource_CollectionChanged;
var tasks = new List<Task>();
for (int i = 1; i < 6; i++)
{
tasks.Add(GetContacts(i.ToString()));
}
await Task.WhenAll(tasks);
}
private void dataSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
List<AlphaKeyGroup<Contact>> DataSource = AlphaKeyGroup<Contact>.CreateGroups(dataSource, System.Threading.Thread.CurrentThread.CurrentUICulture, (Contact s) => { return s.Name; }, true);
ContactsLList.ItemsSource = DataSource;
}
public async Task GetContacts(string page)
{
try
{
string strCredidentials = Globals.APIKey;
string strAuthorization = Convert.ToBase64String(Encoding.UTF8.GetBytes(strCredidentials));
RestClient client = new RestClient(Globals.myURL);
RestRequest request = new RestRequest("/contacts.json?state=all&page=" + page);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Authorization", "Basic " + strAuthorization);
request.Method = Method.GET;
var rslt = client.ExecuteAsync(request, (r) =>
{
if (r.ResponseStatus == ResponseStatus.Completed)
{
if (r.Content == "" || r.Content == " ")
{
MessageBox.Show("No Contacts Found");
}
else
{
dataSource = new ObservableCollection<Contact>();
var conts = JsonConvert.DeserializeObject<List<ContactWrapper>>(r.Content);
foreach (ContactWrapper cont in conts)
{
try
{
string name = cont.User.Name;
string email = cont.User.Email;
string mobile = cont.User.Mobile;
string phone = cont.User.Phone;
string jobtitle = cont.User.JobTitle;
dataSource.Add(new Contact("", "", "", "", "", email, "", jobtitle, mobile, name, phone, ""));
}
catch { }
}
}
}
});
} catch {}
}
}
}
In the GetContacts method the dataSource collection gets added to, so the idea is that GetContacts is called 6 times and each time the return data is added to the dataSource.
When that happens I want to call dataSource_CollectionChanged to update the bound longlistselector on the XAMl page.
Can someone tell me where I am going wrong?
Thanks
I've build a simple example basing on your code and it seems that your code is all right.
I think the problem may be in your Task GetContacts(string page) in // Do stuff here - check if you are not trying to change something within UI if so, do it by using Dispatcher:
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//do UI stuff here;
});
EDIT - it turned out in the discussion that the Collection hadn't beed initialized on start.
i'm working on a windows phone application using pivot view to preview data for the user, the data comes from a web service, then i put it in List then i add the item to the pivot view
but when i call the web service the view doesn't wait till i get the data from the server to add to the view and the view adds nothing , here is my code
public class downloads : List<Downloaded>
{
List<string> downoladedList = new List<string>();
public downloads()
{
BuildCollection();
}
//private const string IMG_PATH = "../Images/";
public ObservableCollection<Downloaded> DataCollection { get; set; }
public ObservableCollection<Downloaded> BuildCollection()
{
// int x=0;
Downloaded downObject = new Downloaded();
ServiceReference1.Service1Client service = new ServiceReference1.Service1Client();
service.GetDownloadsCompleted += new EventHandler<ServiceReference1.GetDownloadsCompletedEventArgs>(GetDownLoads);
System.Threading.Thread.Sleep(100000);
service.GetDownloadsAsync(20019);
DataCollection = new ObservableCollection<Downloaded>();
foreach (var elem in downoladedList)
{
string[] elemProp = new string[8];
elemProp = elem.Split('=');
if (elemProp[3] == "1")
elemProp[3] = "downloaded";
else
elemProp[3] = "in progress";
DataCollection.Add(new Downloaded(elemProp[1], elemProp[3], "test.png"));
}
return DataCollection;
}
public void GetDownLoads(object sender, ServiceReference1.GetDownloadsCompletedEventArgs e)
{
try
{
downoladedList = e.Result.ToList<string>();
}
catch (Exception ee)
{
}
}
}
You cannot call thread.sleep. This will block entire UI thread.
Declare DataCollection = new ObservableCollection();
outside scope.
You should put all your code on completed like this :
public void GetDownLoads(object sender, ServiceReference1.GetDownloadsCompletedEventArgs e)
{
try
{
downoladedList = e.Result.ToList<string>();
foreach (var elem in downoladedList)
{
string[] elemProp = new string[8];
elemProp = elem.Split('=');
if (elemProp[3] == "1")
elemProp[3] = "downloaded";
else
elemProp[3] = "in progress";
DataCollection.Add(new Downloaded(elemProp[1], elemProp[3], "test.png"));
}
}
catch (Exception ee)
{
}
}
I've created several master / detail webparts that need to be connected. We have a requirement the the webparts self discover and connect to other connectable webparts on the page. I've acheived this in a standard ASP.NET page with the following code:
protected override void OnLoad(EventArgs e)
{
WebPartManager manager = WebPartManager.GetCurrentWebPartManager(Page);
manager.StaticConnections.Add(new WebPartConnection()
{
ID = string.Format("WebPartConnection{0}{1}", this.ID, provider.ID),
ConsumerID = this.ID,
ConsumerConnectionPointID = "WebPartConnectableConsumer",
ProviderID = provider.ID,
ProviderConnectionPointID = "WebPartConnectableProvider"
});
}
This approach, however, does not work in SharePoint. Using the SharePoint version of these objects results in a generic sharepoint error:
protected override void OnLoad(EventArgs e)
{
SPWebPartManager spManager = SPWebPartManager.GetCurrentWebPartManager(Page) as SPWebPartManager;
spManager.StaticConnections.Add(new WebPartConnection()
{
ID = string.Format("WebPartConnection{0}{1}", this.ID, provider.ID),
ConsumerID = this.ID,
ConsumerConnectionPointID = "WebPartConnectableConsumer",
ProviderID = provider.ID,
ProviderConnectionPointID = "WebPartConnectableProvider"
});
}
The following approach works, but creates the connection as part of the user's personalization:
protected override void OnLoad(EventArgs e)
{
SPWebPartConnection connection = (from SPWebPartConnection c in spManager.SPWebPartConnections where c != null && c.Consumer == this && c.ConsumerConnectionPointID == "WebPartConnectableConsumer" && c.Provider == provider select c).FirstOrDefault();
if (connection == null)
{
try
{
ProviderConnectionPointCollection providerCollections = spManager.GetProviderConnectionPoints(provider);
ConsumerConnectionPointCollection consumerConnections = spManager.GetConsumerConnectionPoints(this);
connection = spManager.SPConnectWebParts(provider, providerCollections["WebPartConnectableProvider"], this, consumerConnections["WebPartConnectableConsumer"]);
}
catch { }
}
}
Hidden in the logs was an error stating that the StaticConnections property cannot be used in SharePoint/WSS environments. Instead, the SPWebPartConnections property must be used. Moreover, connections must be added prior to the load event (eg. OnInit).
Working code:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
SetUpProviderConnection();
}
private bool SetUpProviderConnection()
{
bool connectionCreated = false;
WebPartManager manager = WebPartManager.GetCurrentWebPartManager(Page);
foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in manager.WebParts)
{
BaseWebPart provider = webPart as BaseWebPart;
if (provider != null && (provider != this))
{
if (manager is Microsoft.SharePoint.WebPartPages.SPWebPartManager)
{
SPWebPartManager spManager = SPWebPartManager.GetCurrentWebPartManager(Page) as SPWebPartManager;
spManager.SPWebPartConnections.Add(new SPWebPartConnection()
{
ID = string.Format("WebPartConnection{0}{1}", this.ID, provider.ID),
ConsumerID = this.ID,
ConsumerConnectionPointID = "WebPartConnectableConsumer",
ProviderID = provider.ID,
ProviderConnectionPointID = "WebPartConnectableProvider"
});
}
else
{
manager.StaticConnections.Add(new WebPartConnection()
{
ID = string.Format("WebPartConnection{0}{1}", this.ID, provider.ID),
ConsumerID = this.ID,
ConsumerConnectionPointID = "WebPartConnectableConsumer",
ProviderID = provider.ID,
ProviderConnectionPointID = "WebPartConnectableProvider"
});
}
connectionCreated = true;
}
}
return connectionCreated;
}