pivot view with dynamic data - c#

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)
{
}
}

Related

Xamarin google Native Ads IOS

I am trying to implement Native ads in xamarin it works fine with android but I have a problem with ios
Here is my code
public class AdMobNativeAdRenderer : ViewRenderer<Controls.NativeAdView, UnifiedNativeAdView>, IAdLoaderDelegate, IUnifiedNativeAdDelegate, IUnifiedNativeAdLoaderDelegate, IVideoControllerDelegate
{
public UnifiedNativeAdView nativeAdView = null;
public void DidReceiveUnifiedNativeAd(AdLoader adLoader, UnifiedNativeAd nativeAd)
{
// A unified native ad has loaded, and can be displayed.
nativeAd.Delegate = this;
// The headline and mediaContent are guaranteed to be present in every native ad.
nativeAdView.NativeAd = nativeAd;
if (nativeAdView.HeadlineView==null)
{
nativeAdView.HeadlineView= new UILabel();
}
(nativeAdView.HeadlineView as UILabel).Text = nativeAd.Headline;
if (nativeAdView.MediaView == null) {
nativeAdView.MediaView = new MediaView();
}
if (nativeAdView.MediaView.MediaContent == null)
{
nativeAdView.MediaView.MediaContent = new MediaContent();
}
nativeAdView.MediaView.MediaContent = nativeAd.MediaContent;
nativeAdView.MediaView.ContentMode = UIViewContentMode.ScaleAspectFill;
if (nativeAdView.BodyView==null)
{
nativeAdView.BodyView = new UILabel();
}
(nativeAdView.BodyView as UILabel).Text = nativeAd.Body;
nativeAdView.BodyView.Hidden = nativeAd.Body == null;
if (nativeAdView.CallToActionView==null)
{
nativeAdView.CallToActionView = new UIButton();
}
(nativeAdView.CallToActionView as UIButton).SetTitle(nativeAd.CallToAction,UIControlState.Normal);
nativeAdView.CallToActionView.Hidden = nativeAd.CallToAction == null;
if (nativeAdView.IconView==null)
{
nativeAdView.IconView = new UIImageView();
}
(nativeAdView.IconView as UIImageView).Image = nativeAd.Icon.Image;
nativeAdView.IconView.Hidden = nativeAd.Icon == null;
if (nativeAdView.StoreView==null)
{
nativeAdView.StoreView = new UILabel();
}
(nativeAdView.StoreView as UILabel).Text = nativeAd.Store;
nativeAdView.StoreView.Hidden = nativeAd.Store == null;
if (nativeAdView.PriceView==null)
{
nativeAdView.PriceView = new UILabel();
}
(nativeAdView.PriceView as UILabel).Text = nativeAd.Price;
nativeAdView.PriceView.Hidden = nativeAd.Price == null;
if (nativeAdView.AdvertiserView==null)
{
nativeAdView.AdvertiserView = new UILabel();
}
if (nativeAdView.StoreView==null)
{
nativeAdView.StoreView = new UILabel();
}
(nativeAdView.StoreView as UILabel).Text = nativeAd.Store;
(nativeAdView.AdvertiserView as UILabel).Text = nativeAd.Advertiser;
nativeAdView.AdvertiserView.Hidden = nativeAd.Advertiser == null;
nativeAdView.CallToActionView.UserInteractionEnabled = false;
nativeAdView.NativeAd = nativeAd;
try
{
nativeAdView.BackgroundColor = UIColor.Green;
SetNativeControl(nativeAdView);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
[Export("adLoaderDidFinishLoading:")]
void DidFinishLoading(AdLoader adLoader)
{
// The adLoader has finished loading ads, and a new request can be sent.
}
public void DidFailToReceiveAd(AdLoader adLoader, RequestError error)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Controls.NativeAdView> e)
{
base.OnElementChanged(e);
try
{
if (e.OldElement != null)
{
try
{
e.OldElement.Content=null;
}
catch (Exception)
{
}
SetNativeControl(nativeAdView);
}
if (e.NewElement != null)
{
if (Control == null)
{
// Instantiate the native control and assign it to the Control property with
CreateAdView();
try
{
e.NewElement.Content = null;
}
catch (Exception)
{
}
SetNativeControl(nativeAdView);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
AdLoader adLoader;
private void CreateAdView()
{
//if (Element == null) return;
var multipleAdsOptions = new MultipleAdsAdLoaderOptions { NumberOfAds = 1 };
adLoader = new AdLoader("ca-app-pub-3940256099942544/3986624511", GetVisibleViewController(), new[] { AdLoaderType.UnifiedNative }, new[] { multipleAdsOptions })
{
Delegate = this
};
var request = Request.GetDefaultRequest();
request.TestDevices = new string[] { Request.SimulatorId };
if (nativeAdView == null)
{
nativeAdView = new UnifiedNativeAdView();
};
try
{
adLoader.LoadRequest(request);
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
Debug.WriteLine("Loading: " + adLoader.IsLoading);
}
private UIViewController GetVisibleViewController()
{
var windows = UIApplication.SharedApplication.Windows;
foreach (var window in windows)
{
if (window.RootViewController != null)
{
return window.RootViewController;
}
}
return null;
}
}
Every thing is working as anticipated and I receive the ad and the event DidReceiveUnifiedNativeAd fires but I get an empty ad although when I debug the code I see that the content of the ad is not empty and the control color is green so the control is loaded but why it doesn't show the ad content
Please can anyone help is solving this

Realm/Xamarin.Forms/Android/C#: Data not being saved across runs

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.

WP8 ObservableCollection.CollectionChanged delegate crashing

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.

How to insert a record in lambda expression and possible way to shorten the length of code

private void SaveNewLogsheet01Record()
{
try
{
Logsheet01 Header = new Logsheet01();
Header.DrNO = drNO.Text;
Header.DocDate = dtPicker.Value;
Header.RecNum = RecNum.Value;
Header.DocuTitle = DocumentHeader.Text;
SaveRec01(Header);
}
catch (Exception) { }
}
private void SaveNewLogsheet02Record()
{
try
{
Logsheet02 Details = new Logsheet02();
Details.RecNum = RecNum.Value;
Details.DataFile01 = GlobalVar.DataRec01;
Details.DataFile02 = GlobalVar.DataRec02;
Details.DataFile03 = GlobalVar.DataRec03;
Details.UserName = GlobalVar.UserInfo;
SaveRec02(Details);
}
catch (Exception) { }
}
private void SaveRec01(Logsheet01 Header) <-- is this necessary in c#?
{
try
{
using (DBDataContext DB = new DBDataContext())
{
DB.Delivery_HeaderRECs.InsertOnSubmit(Header);
DB.SubmitChanges();
DB.Connection.Close();
}
}
catch (Exception) { }
}
private void SaveRec02(Logsheet02 Header)
{
try
{
using (DBDataContext DB = new DBDataContext())
{
DB.Logsheet0.InsertOnSubmit(Header);
DB.SubmitChanges();
DB.Connection.Close();
}
}
catch (Exception) { }
}
i just want to find a new way on how to insert a
record on database make my codes cleaner and shorter now if i have a
form with multiple insert on tables ex.: Tables like "Logsheet01" and
"Logsheet02" , "Logsheet03" and i want my codes to be shorten. is
there a way i can put in the saveRec01 Function into one function for
3 tables?
is there a way i could make like this:
private void SaveRec01(Logsheet01 Header)
{
if(Saving == "Logsheet01") {
using(DBDatacontex DB = new DBDatacontex) {
DB.Logsheet01.InsertOnSubmit(Header);
DB.SubmitChanges();
DB.Connection.Close();
}
}elseif (Saving == "Logsheet02") {
using(DBDatacontex DB = new DBDatacontex) {
DB.Logsheet02.InsertOnSubmit(Header);
DB.SubmitChanges();
DB.Connection.Close();
}
} //etc..
}
or maybe a new lambda expression of insert a record list?
If you wish to get rid of the repetitive code and only specify the "meat" of the database operation each time, you can move all your boilerplate code into a method which accepts an Action that defines the variable component of your operation like so:
// Wrapper for our database operation.
private void PerformDbOperationAndSubmit(Action<DBDataContext> action)
{
using (DBDataContext DB = new DBDataContext())
{
// Invoke our arbitrary action over the data context.
action(DB);
DB.SubmitChanges();
DB.Connection.Close();
}
}
// Object creation (modified for the sake of brevity).
private void SaveNewLogsheet01Record()
{
Logsheet01 Header = new Logsheet01();
// Fill Header properties here.
PerformDbOperationAndSubmit(dx => dx.Delivery_HeaderRECs.InsertOnSubmit(Header));
}
private void SaveNewLogsheet02Record()
{
Logsheet02 Details = new Logsheet02();
// Fill Details properties here.
PerformDbOperationAndSubmit(dx => dx.Logsheet0.InsertOnSubmit(Details));
}
You can write:
Logsheet01 Header = new Logsheet01({
DrNO = drNO.Text,
DocDate = dtPicker.Value,
RecNum = RecNum.Value,
DocuTitle = DocumentHeader.Text
});
Header.SaveRecord();
Create a function like this one:
private void SaveRecord()
{
using(DBDatacontex DB = new DBDatacontex) {
//I used this because the SaveRecord function is in the same class as the object used to create the record
DB.Delivery_HeaderRECs.InsertOnSubmit(this);
DB.SubmitChanges(); }
}
}

How to update and delete a specific line from a text file in C# windows form [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am new in using file handler in c#. I have done insert and search. Please help me how can I do update and delete using this following code.
UI part::
private void btnAdd1_Click(object sender, EventArgs e)
{
StudentManager sm = new StudentManager();
sm.AddStudent(textName.Text,textId.Text,textDpt.Text,textSem.Text);
}
public void btnSearch1_Click(object sender, EventArgs e)
{
StudentManager sm = new StudentManager();
Student s = sm.FindStudent(textId.Text);
if (s != null)
{
this.textName.Text = s.GetName();
this.textId.Text = s.ID;
this.textDpt.Text = s.Department;
this.textSem.Text = s.GetSEM();
}
}
validation::
string id = String.Empty;
public void SetName(string name)
{
if(!String.IsNullOrEmpty(name))
{
this.name = name;
}
}
public string ID
{
get { return id; }
set { id = value; }
}
string department = String.Empty;
public string Department
{
get { return department; }
set { department = value; }
}
string SEM= String.Empty;
public void SetSEM(string sem)
{
if (!String.IsNullOrEmpty(sem))
{
this.SEM = sem;
}
}
public string GetSEM()
{
return this.SEM;
}
public String GetName()
{
return this.name;
}
}
studentManager::
class StudentManager
{
ArrayList students;
const string FILENAME = #"d:\students.txt";
public StudentManager()
{
SetStudentList();
}
private void SetStudentList()
{
if (students == null)
{
//create a file handler
FileHandler sfh = new FileHandler();
//initialize the teacher list object
students = new ArrayList();
//Now read all the lines from the teacher.txt
//each line represent a teacher
string[] studentfromfile = sfh.getAllLines(#FILENAME);
int totalstudents = studentfromfile.Length;
//go through each teacher and create teacher object to add it to the teacher list.
for (int i = 0; i < totalstudents; i++)
{
string studentinfo = studentfromfile[i];
string[] studentinfobroken = studentinfo.Split(new char[] { ',' });
if (studentinfobroken.Length == 4)
{
//this part is being duplicated - can think how?
Student s = new Student();
s.SetName(studentinfobroken[0]);
s.ID= studentinfobroken[1];
s.Department = studentinfobroken[2];
s.SetSEM(studentinfobroken[3]);
this.students.Add(s);
}
}
}
}
public void AddStudent(string fullname, string ID, string dept,string Semester )
{
Student s = new Student();
s.SetName(fullname);
s.ID = ID;
s.Department = dept;
s.SetSEM(Semester);
this.students.Add(s);
FileHandler sfh = new FileHandler();
string studentInfo = Environment.NewLine + s.GetName() + "," + s.ID + "," + s.Department + "," + s.GetSEM();
sfh.AddLine(#FILENAME, studentInfo);
}
public Student FindStudent(string ID)
{
foreach (Student s in students)
{
if (s.ID.Equals(ID))
{
return s;
}
}
return null;
}
class FileHandler
{
public String[] getAllLines(string fileName)
{
try
{
String[] lines = File.ReadAllLines(#fileName);
return lines;
}
catch (Exception e)
{
throw e;
}
}
public String GetAllText(string fileName)
{
try
{
String content = File.ReadAllText(#fileName);
return content;
}
catch (Exception e)
{
throw e;
}
}
public void AddLine(string filename, string line)
{
StreamWriter sr = null;
try
{
sr = new StreamWriter(#filename, true);//true for append
sr.WriteLine(line);
}
catch (Exception e)
{
throw e;
}
finally
{
sr.Close();
}
}
Ok I've looked over your code and it looks as though you update your textfile after every little thing you do which is the wrong approach.. (If I'm wrong then please reduce the code in your example to make it easier to read!)
What you should be trying to do is when your program loads, load the students from the file into a list of Students. Then whilst your program persists you should use this list wherever you need it. When you are ready to close your program, then you write it back to the file.
One advantage of this way, other than the obvious efficiency and ease of use, is that changes can be cancelled without your only copy of students being destroyed.
e.g
studentList.Remove(student) - Remove from list
studentList.Add(student) - add
studentList.Where(x => x.Name = "Joe"); - Filter
Update
studentfromfile[5] = "updated line";
File.WriteAllLines(FILENAME, studentfromfile);
Delete
studentfromfile[5] = String.Empty;
studentfromfile = studentfromfile.Where(x => !String.IsNullOrEmpty(x)).ToArray();
File.WriteAllLines(FILENAME, studentfromfile);
There are better ways of doing this such as using a collection as Sayse recommends. You shouldn't use ArrayLists, they're not required if you're creating a project that targets .Net 2.0 and above (use List), and you shouldn't throw exceptions like that because you're losing the stacktrace. Use
try
{
String content = File.ReadAllText(#fileName);
return content;
}
catch (Exception e)
{
throw; //not throw e;
}

Categories

Resources