xamarin forms dynamic image tapgesture recognizer control - xamarin

How can I provide control (change) of my dynamic images created in xamarin forms by clicking?
Image ggImage = new Image()
ggImage.Source = otoTip.imagex
ggImage.AutomationId = "seat_" +otoTip.num
ggImage.WidthRequest = imageWidth
ggImage.HeightRequest = 50
ggImage.VerticalOptions = LayoutOptions.Start
ggImage.HorizontalOptions = LayoutOptions.Start
ggImage.GestureRecognizers.Add(tapGestureRecognizer)
For example, I just want to change a resume source.

You have to implement a TapGestureRecognizer and then add it to your image...
Image ggImage = new Image();
ggImage.Source = otoTip.imagex
ggImage.AutomationId = "seat_" +otoTip.num
ggImage.WidthRequest = imageWidth
ggImage.HeightRequest = 50;
ggImage.VerticalOptions = LayoutOptions.Start;
ggImage.HorizontalOptions = LayoutOptions.Start;
// your TapGestureRecognizer implementation, this is just a sample...
var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += (s, e) => { ggImage.Source = yourNewSource };
ggImage.GestureRecognizers.Add(tapGestureRecognizer);
In order to change every unique image of your dynamically created images you could extend your OtoTip class and
public class OtoTip : INotifyPropertyChanged
{
public int x { get; set; }
public int y { get; set; }
public int num { get; set; }
public int near { get; set; }
public int status { get; set; }
public int yy { get; set; }
public int xx { get; set; }
// xx
private string _imagex;
public string imagex
{
get { return _imagex; }
set
{
_imagex = value;
OnPropertyChanged(nameof(imagex));
}
}
private string _imageActivex;
public string imageActivex
{
get { return _imageActivex; }
set
{
_imageActivex = value;
OnPropertyChanged(nameof(imageActivex));
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
You have to extend your getVoyagesData() now, to also set the imageActivex like your standard image.
Now you have to adjust the TapGestureRecognizer to use the new property
tapGestureRecognizer.Tapped += (s, e) =>
{
if(ggImage.Source = otoTip.imagex) {
ggImage.Source = otoTip.imageActivex;
}
else
{
ggImage.Source = otoTip.imagex;
}
};
Does this help?

Related

Xamarin.Forms MVVM WebView not Loading

We use the Xamarin.Forms WebView to display content of a certain object, but this content won't be displayed in the WebView until we rotate the Device twice.
The .xmal-File Code:
<WebView x:Name="WebView" HeightRequest="{Binding Height}" WidthRequest="{Binding Width}">
<WebView.Source>
<HtmlWebViewSource Html="{Binding Code}"/>
</WebView.Source>
</WebView>
And the ModelView:
private double _height;
private double _width;
public ICommand ItemTappedCommand { get; private set; }
public string SearchBarLabelText { get; private set; }
public object LastTappedItem { get; set; }
public int ColumnCount { get; private set; } = 2;
public string CodeName { get; private set; }
public string CodeContent { get; private set; }
public string Code { get; private set; }
public double Height
{
get => _height;
private set
{
if (_height == value)
return;
_height = value;
OnPropertyChanged(nameof(Height));
}
}
public double Width
{
get => _width;
private set
{
if (_width == value)
return;
_width = value;
OnPropertyChanged(nameof(Width));
}
}
public ErrorcodeDetailPageViewModel(Errorcode code)
{
Device.Info.PropertyChanged += DevicePropertyChanged;
DevicePropertyChanged(null, null);
Code = code.Content;
CodeName = code.Label;
CodeContent = code.Content;
}
private void DevicePropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (Device.Info.CurrentOrientation)
{
case DeviceOrientation.Portrait:
Height = Device.Info.PixelScreenSize.Height - 150; // 120 is the Height of the ControlTemplate used on this Page + the top row on uwp; only required in portrait mode
Width = Device.Info.PixelScreenSize.Width;
break;
case DeviceOrientation.Landscape:
Height = Device.Info.PixelScreenSize.Height - 50;
Width = Device.Info.PixelScreenSize.Width;
break;
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
So, als already described, if we rotate the Device twice the content will be displayed, otherwise it won't. I think the problem is related to our bindings...
I should mention that we have some kind ob banner/headline on top of the WebView.
Code should also have a backing notification so that the view is aware of when its value changes.
Like
private string code;
public string Code {
get => code;
private set {
if (code == value)
return;
code = value;
OnPropertyChanged(nameof(Code));
}
}
If you walk through the step of why you have to turn twice, you will see that is why you have to do that.
When the value is first set it is blank.
On first turn the value is set by the event handler not since no notification is sent to the view it is not visibly changed.
On second turn the value is already set and when the view redraws, the value is shown in the view.

Adding Left Border line in itextsharp

I was facing issue to work on rowspan but with some code in C#, I was able to achieve that. Currently I have the data what I needed.
How can I draw left border line for the first column so that it looks correct.
here is what I have now.
I need to add left border line.
here is my code:
{
ReportTableCell cell = null;
// prevent null values from crashing the system (always a good idea)
if (text == null)
{
text = string.Empty;
}
// else already valid
ReportTable.CreateReportTableCell(text, out cell);
cell.RowSpan = row_span;
cell.ColumnSpan = column_span;
cell.Style.WrapText = true;
cell.Style.BorderWidth = border_width;
// cell.Style.BorderColor = CellBorderColor.Gray;
if ( repeated)
{
// cell.Style.Border = BOTTOM_BORDER;
cell.Style.BorderWidth = border_width;
}
else
{
cell.Style.BorderWidth = 0;
repeated = true;
}
cell.Style.Font.FontStyle = font_style;
cell.Style.Font.FontSize = font_size;
cell.Style.BackgroundColor = background_color;
cell.Style.IsColumnHeader = is_column_header;
cell.Style.HorizontalAlignment = horizontal_alignment;
if (is_column_header)
{
cell.Style.VerticalAlignment = VerticalCellAlignment.Middle;
}
else
{
cell.Style.VerticalAlignment = VerticalCellAlignment.Top;
}
repeated = true;
return cell;
}
based on the condition i.e.
if ( repeated){}
I am removing border, which I know it has removed border around 4 corners, how can i append an extra line only for the left side.
UPDATE : 1
after using the code as below :
if ( repeated)
{
cell.Style.BorderWidth = border_width;
}
else
{
cell.Style.BorderWidth = 0;
cell.Style.Border = BOTTOM_BORDER | LEFT_BORDER;
repeated = true;
}
changed nothing!.
Here is the base class of the report.
public class ReportTableCell
{
public static readonly int ALL_BORDER;
public static readonly int BOTTOM_BORDER;
public static readonly int LEFT_BORDER;
public static readonly int NO_BORDER;
public static readonly int RIGHT_BORDER;
public static readonly int TOP_BORDER;
public bool AllowBlanks { get; set; }
public int ColumnSpan { get; set; }
public ReportFont Font { get; set; }
public int RowSpan { get; set; }
public TableCellStyle Style { get; set; }
public ReportTable Table { get; set; }
public object Value { get; set; }
public void AddImage(string FileName);
}
UPDATE : 2
I have changed the code as you suggested but , I just have to add single border line to the last. this is what i achieved till now :

Xamarin, Both ListView and RecyclerView, click one item, another one selected

I'm having a trouble with both ListView and RecyclerView
Initially, I created a ListView, everything is fine. Then I set onClick event for it so that every time I click an item, it changes its color to yellow. The OnClick function I wrote in the MainActivity. Problem is that when I test, not only that item changes its color but 2 items change. I read that it's because I reuse the view.
So I switch my tactics, using RecyclerView instead but same problem occurs. When I click one item to change its color, another below also changes. I guess it's because both ListView and RecyclerView reuse those Item so they confuse when I click one.
I don't know how to solve this problem, I found a solution is to add an array of boolean which marks which item is clicked but it doesn't work. Any idea guys?
So here is the code
MainActivity
class MainActivity : Activity
{
public RecyclerView recyclerView;
public RecyclerView.LayoutManager manager;
public RecyclerView.Adapter adapter;
List<Row> lst;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
init();
recyclerView = (RecyclerView)FindViewById(Resource.Id.recyclerView);
manager = new LinearLayoutManager(this);
recyclerView.SetLayoutManager(manager);
CustomAdapter adapter = new CustomAdapter(lst, this);
adapter.ItemClick += onItemClick;
recyclerView.SetAdapter(adapter);
}
public void init()
{
lst = new List<Row>();
for (int i = 0; i < 15; i++)
{
Row row = new Row() { field1="1:43:00", field2="09-Apr-16", field3="KPI/Overflow", field4="Kevin Bacon", field5="Unowned", field6= "People Counting # IPCAM-ID-C-1-1" };
lst.Add(row);
}
}
public void onItemClick(object sender, int position)
{
int itemPos = position + 1;
//Toast.MakeText(this, "this is " + itemPos, ToastLength.Short).Show();
recyclerView.GetChildAt(position).SetBackgroundColor(Android.Graphics.Color.Green);
}
}
Custom adapter
public class CustomAdapter : RecyclerView.Adapter
{
public Activity _activity;
public List<Row> lst;
public event EventHandler<int> ItemClick;
public CustomAdapter(List<Row> lst, Activity activity)
{
this.lst = lst;
this._activity = activity;
}
public override int ItemCount
{
get
{
return lst.Count;
}
}
public void OnClick(int position)
{
if (ItemClick!=null)
{
ItemClick(this, position);
}
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
MyViewHolder myholder = holder as MyViewHolder;
myholder.textView1.Text = lst[position].field1;
myholder.textView2.Text = lst[position].field2;
myholder.textView3.Text = lst[position].field3;
myholder.textView4.Text = lst[position].field4;
myholder.textView5.Text = lst[position].field5;
myholder.textView6.Text = lst[position].field6;
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View v = this._activity.LayoutInflater.Inflate(Resource.Layout.item, parent, false);
TextView tv1 = (TextView)v.FindViewById(Resource.Id.textView1);
TextView tv2 = (TextView)v.FindViewById(Resource.Id.textView2);
TextView tv3 = (TextView)v.FindViewById(Resource.Id.textView3);
TextView tv4 = (TextView)v.FindViewById(Resource.Id.textView4);
TextView tv5 = (TextView)v.FindViewById(Resource.Id.textView5);
TextView tv6 = (TextView)v.FindViewById(Resource.Id.textView6);
MyViewHolder holder = new MyViewHolder(v, OnClick) { textView1 = tv1, textView2 = tv2, textView3 = tv3, textView4 = tv4, textView5 = tv5, textView6 = tv6 };
return holder;
}
}
class MyViewHolder : RecyclerView.ViewHolder
{
public TextView textView1, textView2, textView3, textView4, textView5, textView6;
public View mainView;
public MyViewHolder(View view, Action<int> listener) : base(view)
{
mainView = view;
mainView.Click += (sender, e) => listener(base.Position);
}
}
I followed the example for the OnClick handler on Xamarin site
https://developer.xamarin.com/guides/android/user_interface/recyclerview/
Your issue is with your code. You send the correct position to your event handler, but then you increment it by one in the Activity. Both ends should be using the 0-based index of the item position. There is no need to increment by one.
For changing the background color of the selected item, you can use a selector in XML so you wouldn't even need to do this in code.
Here is an example.
row_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="#android:color/green" />
<item android:state_selected="false" android:color="#android:color/transparent"/>
</selector>
row_content.axml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/row_layout_parent"
android:background="#drawable/row_selector">
<!-- your row content -->
</LinearLayout>
Then your view holder would be updated to this...
class MyViewHolder : RecyclerView.ViewHolder
{
public TextView textView1, textView2, textView3, textView4, textView5, textView6;
public View mainView;
private LinearLayout _layoutParent;
public MyViewHolder(View view, Action<int> listener) : base(view)
{
mainView = view;
_layoutParent = mainView.FindViewById<LinearLayout>(Resource.Id.row_layout_parent);
_layoutParent.Click += (sender, e) => _layoutParent.Selected = true;
}
}
I removed the other click event. If you still need it for other reasons, then you can add it back, but it's not necessary for just setting the item background color when selected.
For Listview you should set choiceMode as below.
listView.ChoiceMode = ChoiceMode.Single;
Hope it help you :)-
Create a reusable recycleview adapter GENERIC
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Support.V7.App;
using Android.Support.V7.Widget;
using Android.Text;
using Android.Text.Style;
using Android.Util;
using Android.Views;
using Android.Widget;
using Java.Util.Zip;
using ActionMenuView = Android.Support.V7.Widget.ActionMenuView;
namespace Android.Basic.Core
{
public class GenericRecyclerViewAdapter<T> : RecyclerView.Adapter
{
/// <summary>
/// You can set this for different custom cardview
/// </summary>
private int CardViewResourceLayout { get; set; }
public ObservableCollection<T> Items { get; private set; }
public event EventHandler<RecyclerViewViewHolder> ItemViewTemplated;
public RecyclerView.LayoutManager layoutManager;
public GenericRecyclerViewAdapter(RecyclerView recyclerView, IEnumerable<T> items, int cardViewResourceLayout, bool isList = true, bool isVertical = true) : base()
{
if(isList)
{
var vertical = isVertical ? LinearLayoutManager.Vertical : LinearLayoutManager.Horizontal;
layoutManager = new LinearLayoutManager(recyclerView.Context, vertical, false);
}
else
{
var vertical = isVertical ? GridLayoutManager.Vertical : GridLayoutManager.Horizontal;
layoutManager = new GridLayoutManager(recyclerView.Context, 3, vertical, false);
}
recyclerView.SetLayoutManager(layoutManager);
this.Items = new ObservableCollection<T>(items);
this.CardViewResourceLayout = cardViewResourceLayout;
this.Items.CollectionChanged += delegate
{
this.NotifyDataSetChanged();
};
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
var itemView = LayoutInflater.From(parent.Context).Inflate(CardViewResourceLayout, parent, false);
#if DEBUG
Log.Info("GenericRecyclerViewAdapter - ", CardViewResourceLayout.ToString());
#endif
RecyclerViewViewHolder vh = new RecyclerViewViewHolder(itemView);
return vh;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
RecyclerViewViewHolder vh = holder as RecyclerViewViewHolder;
vh.ItemPosition = position;
vh.TemplateView.Tag = position;
vh.TemplateView.Click -= TemplateView_Click;
vh.TemplateView.Click += TemplateView_Click;
ItemViewTemplated?.Invoke(this, vh);
}
public event EventHandler<T> ItemClicked;
private void TemplateView_Click(object sender, EventArgs e)
{
var position = (int)((View)sender).Tag;
this.ItemClicked?.Invoke(sender, this.Items[position]);
}
public override int ItemCount
{
get { return this.Items.Count; }
}
public override long GetItemId(int position)
{
return base.GetItemId(position);
}
}
public class RecyclerViewViewHolder : RecyclerView.ViewHolder, View.IOnCreateContextMenuListener,
IMenuItemOnMenuItemClickListener
{
public View TemplateView { get; private set; }
public int ItemPosition { get; set; }
public event EventHandler<MenuInfo> ContextMenuCreated;
public event EventHandler<object> MenuItemClicked;
public MenuInfo MenuInfo { get; private set; }
public object Data { get; set; }
public RecyclerViewViewHolder(View itemView) : base(itemView)
{
// Locate and cache view references:
this.TemplateView = itemView;
this.TemplateView.SetOnCreateContextMenuListener(this);
}
public void OnCreateContextMenu(IContextMenu menu, View v, IContextMenuContextMenuInfo menuInfo)
{
MenuInfo = new MenuInfo(menu, v, menuInfo);
ContextMenuCreated?.Invoke(this, MenuInfo);
}
private Android.Views.MenuInflater menuInflater = null;
/// <summary>
/// After ContextMenuCreated
/// </summary>
/// <param name="resourcemenu"></param>
public void InflateMenu(int resourcemenu, SpannableString titleColor = null, object dta = null)
{
if (dta != null)
this.Data = dta;
if (this.TemplateView.Context is AppCompatActivity activity)
{
menuInflater = activity.MenuInflater;
}
else if (this.TemplateView.Context is Activity activity2)
{
menuInflater = activity2.MenuInflater;
}
var contextMenu = this.MenuInfo.ContextMenu;
contextMenu.Clear();
menuInflater.Inflate(resourcemenu, contextMenu);
var num = contextMenu.Size() - 1;
for (int i = 0; i <= num; i++)
{
var men = contextMenu.GetItem(i);
if(titleColor != null)
{
if (i == 0)
{
men.SetTitle(titleColor);
men.SetChecked(true);
}
}
if (i != 0)
{
men.SetOnMenuItemClickListener(this);
}
}
}
public bool OnMenuItemClick(IMenuItem item)
{
this.MenuItemClicked?.Invoke(item, this.Data);
return true;
}
public float PosX;
public float PosY;
}
public class MenuInfo
{
public IContextMenu ContextMenu { get; }
public View View { get; }
public IContextMenuContextMenuInfo ContextMenuInfo { get; }
public MenuInfo(IContextMenu contextMenu, View view, IContextMenuContextMenuInfo menuInfo)
{
this.ContextMenu = contextMenu;
this.View = view;
this.ContextMenuInfo = menuInfo;
}
}
}
Usage
RecyclerView recyclerView = new RecyclerView(this);
var viewAdapter = new Android.Basic.Core.GenericRecyclerViewAdapter<Java.IO.File>(recyclerView, files, Resource.Layout.directory_item);
var indiColor = ThemeHelper.IsDark ? ColorHelper.GetRandomLightColor() : ColorHelper.GetRandomDarkColor();
viewAdapter.ItemViewTemplated += (dd, holder) =>
{
var file = files[holder.ItemPosition];
var view = holder.ItemView;
var expanded = view.FindViewById<ExpandedView>(Resource.Id.expandedView);
expanded.SetToggleColor(indiColor);
expanded.SetTitle(file.Name);
GenerateRecycler(expanded, file);
};
recyclerView.SetAdapter(viewAdapter);
expandedView.AddExpandedView(recyclerView);

How to send complex objects in GET to WEB API 2

Let's say that you have the following code
public class MyClass {
public double Latitude {get; set;}
public double Longitude {get; set;}
}
public class Criteria
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public MyClass MyProp {get; set;}
}
[HttpGet]
public Criteria Get([FromUri] Criteria c)
{
return c;
}
I'd like to know if someone is aware of a library that could transform any object into query string that is understood by a WEB API 2 Controller.
Here is an example of what I'd like
SerializeToQueryString(new Criteria{StartDate=DateTime.Today, EndDate = DateTime.Today.AddDays(1), MyProp = new MyProp{Latitude=1, Longitude=3}});
=> "startDate=2015-10-13&endDate=2015-10-14&myProp.latitude=1&myProp.longitude=3"
A full example with httpClient might look like :
new HttpClient("http://localhost").GetAsync("/tmp?"+SerializeToQueryString(new Criteria{StartDate=DateTime.Today, EndDate = DateTime.Today.AddDays(1), MyProp = new MyProp{Latitude=1, Longitude=3}})).Result;
At the moment, I use a version (taken from a question I do not find again, maybe How do I serialize an object into query-string format? ...).
The problem is that it is not working for anything else than simple properties.
For example, calling ToString on a Date will not give something that is parseable by WEB API 2 controller...
private string SerializeToQueryString<T>(T aObject)
{
var query = HttpUtility.ParseQueryString(string.Empty);
var fields = typeof(T).GetProperties();
foreach (var field in fields)
{
string key = field.Name;
var value = field.GetValue(aObject);
if (value != null)
query[key] = value.ToString();
}
return query.ToString();
}
"Transform any object to a query string" seems to imply there's a standard format for this, and there just isn't. So you would need to pick one or roll your own. JSON seems like the obvious choice due to the availability of great libraries.
Since it seems no one has dealt with the problem before, here is the solution I use in my project :
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using System.Web;
namespace App
{
public class QueryStringSerializer
{
public static string SerializeToQueryString(object aObject)
{
return SerializeToQueryString(aObject, "").ToString();
}
private static NameValueCollection SerializeToQueryString(object aObject, string prefix)
{
//!\ doing this to get back a HttpValueCollection which is an internal class
//we want a HttpValueCollection because toString on this class is what we want in the public method
//cf http://stackoverflow.com/a/17096289/1545567
var query = HttpUtility.ParseQueryString(String.Empty);
var fields = aObject.GetType().GetProperties();
foreach (var field in fields)
{
string key = string.IsNullOrEmpty(prefix) ? field.Name : prefix + "." + field.Name;
var value = field.GetValue(aObject);
if (value != null)
{
var propertyType = GetUnderlyingPropertyType(field.PropertyType);
if (IsSupportedType(propertyType))
{
query.Add(key, ToString(value));
}
else if (value is IEnumerable)
{
var enumerableValue = (IEnumerable) value;
foreach (var enumerableValueElement in enumerableValue)
{
if (IsSupportedType(GetUnderlyingPropertyType(enumerableValueElement.GetType())))
{
query.Add(key, ToString(enumerableValueElement));
}
else
{
//it seems that WEB API 2 Controllers are unable to deserialize collections of complex objects...
throw new Exception("can not use IEnumerable<T> where T is a class because it is not understood server side");
}
}
}
else
{
var subquery = SerializeToQueryString(value, key);
query.Add(subquery);
}
}
}
return query;
}
private static Type GetUnderlyingPropertyType(Type propType)
{
var nullablePropertyType = Nullable.GetUnderlyingType(propType);
return nullablePropertyType ?? propType;
}
private static bool IsSupportedType(Type propertyType)
{
return SUPPORTED_TYPES.Contains(propertyType) || propertyType.IsEnum;
}
private static readonly Type[] SUPPORTED_TYPES = new[]
{
typeof(DateTime),
typeof(string),
typeof(int),
typeof(long),
typeof(float),
typeof(double)
};
private static string ToString(object value)
{
if (value is DateTime)
{
var dateValue = (DateTime) value;
if (dateValue.Hour == 0 && dateValue.Minute == 0 && dateValue.Second == 0)
{
return dateValue.ToString("yyyy-MM-dd");
}
else
{
return dateValue.ToString("yyyy-MM-dd HH:mm:ss");
}
}
else if (value is float)
{
return ((float) value).ToString(CultureInfo.InvariantCulture);
}
else if (value is double)
{
return ((double)value).ToString(CultureInfo.InvariantCulture);
}
else /*int, long, string, ENUM*/
{
return value.ToString();
}
}
}
}
Here is the unit test to demonstrate :
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Framework.WebApi.Core.Tests
{
[TestClass]
public class QueryStringSerializerTest
{
public class EasyObject
{
public string MyString { get; set; }
public int? MyInt { get; set; }
public long? MyLong { get; set; }
public float? MyFloat { get; set; }
public double? MyDouble { get; set; }
}
[TestMethod]
public void TestEasyObject()
{
var queryString = QueryStringSerializer.SerializeToQueryString(new EasyObject(){MyString = "string", MyInt = 1, MyLong = 1L, MyFloat = 1.5F, MyDouble = 1.4});
Assert.IsTrue(queryString.Contains("MyString=string"));
Assert.IsTrue(queryString.Contains("MyInt=1"));
Assert.IsTrue(queryString.Contains("MyLong=1"));
Assert.IsTrue(queryString.Contains("MyFloat=1.5"));
Assert.IsTrue(queryString.Contains("MyDouble=1.4"));
}
[TestMethod]
public void TestEasyObjectNullable()
{
var queryString = QueryStringSerializer.SerializeToQueryString(new EasyObject() { });
Assert.IsTrue(queryString == "");
}
[TestMethod]
public void TestUrlEncoding()
{
var queryString = QueryStringSerializer.SerializeToQueryString(new EasyObject() { MyString = "&=/;+" });
Assert.IsTrue(queryString.Contains("MyString=%26%3d%2f%3b%2b"));
}
public class DateObject
{
public DateTime MyDate { get; set; }
}
[TestMethod]
public void TestDate()
{
var d = DateTime.ParseExact("2010-10-13", "yyyy-MM-dd", CultureInfo.InvariantCulture);
var queryString = QueryStringSerializer.SerializeToQueryString(new DateObject() { MyDate = d });
Assert.IsTrue(queryString.Contains("MyDate=2010-10-13"));
}
[TestMethod]
public void TestDateTime()
{
var d = DateTime.ParseExact("2010-10-13 20:00", "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
var queryString = QueryStringSerializer.SerializeToQueryString(new DateObject() { MyDate = d });
Assert.IsTrue(queryString.Contains("MyDate=2010-10-13+20%3a00%3a00"));
}
public class InnerComplexObject
{
public double Lat { get; set; }
public double Lon { get; set; }
}
public class ComplexObject
{
public InnerComplexObject Inner { get; set; }
}
[TestMethod]
public void TestComplexObject()
{
var queryString = QueryStringSerializer.SerializeToQueryString(new ComplexObject() { Inner = new InnerComplexObject() {Lat = 50, Lon = 2} });
Assert.IsTrue(queryString.Contains("Inner.Lat=50"));
Assert.IsTrue(queryString.Contains("Inner.Lon=2"));
}
public class EnumerableObject
{
public IEnumerable<int> InnerInts { get; set; }
}
[TestMethod]
public void TestEnumerableObject()
{
var queryString = QueryStringSerializer.SerializeToQueryString(new EnumerableObject() {
InnerInts = new[] { 1,2 }
});
Assert.IsTrue(queryString.Contains("InnerInts=1"));
Assert.IsTrue(queryString.Contains("InnerInts=2"));
}
public class ComplexEnumerableObject
{
public IEnumerable<InnerComplexObject> Inners { get; set; }
}
[TestMethod]
public void TestComplexEnumerableObject()
{
try
{
QueryStringSerializer.SerializeToQueryString(new ComplexEnumerableObject()
{
Inners = new[]
{
new InnerComplexObject() {Lat = 50, Lon = 2},
new InnerComplexObject() {Lat = 51, Lon = 3},
}
});
Assert.Fail("we should refuse something that will not be understand by the server");
}
catch (Exception e)
{
Assert.AreEqual("can not use IEnumerable<T> where T is a class because it is not understood server side", e.Message);
}
}
public enum TheEnum : int
{
One = 1,
Two = 2
}
public class EnumObject
{
public TheEnum? MyEnum { get; set; }
}
[TestMethod]
public void TestEnum()
{
var queryString = QueryStringSerializer.SerializeToQueryString(new EnumObject() { MyEnum = TheEnum.Two});
Assert.IsTrue(queryString.Contains("MyEnum=Two"));
}
}
}
I'd like to thank all the participants even if this is not something that you should usually do in a Q&A format :)

WPhone 7 listbox update from XML

I am having a problem with my Listbox not updating/refresing.I have read here that i need to use ObservableCollection but i didn't have any luck.I am populating my Listbox from a XML.
public class PestotoraPost
{
public string ID { get; set; }
public string Date { get; set; }
public string Name { get; set; }
public string Message { get; set; }
}
void WebLoad()
{
WebClient pestotora = new WebClient();
pestotora.DownloadStringCompleted += new DownloadStringCompletedEventHandler(pestotora_DownloadStringCompleted);
pestotora.DownloadStringAsync(new Uri("wwww.someURL.com/xml.php"));
}
Note that the actual xml is a php containing the xml structure (from a sql DB)
void pestotora_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
XElement doc = XElement.Parse(e.Result);
listBox1.ItemsSource = from results in doc.Descendants("Data")
select new PestotoraPost
{
ID = results.Element("DataID").Value,
Date = results.Element("DataDate").Value,
Name=results.Element("DataName").Value,
Message=results.Element("DataMessage").Value
};
}
Everytime the XML changes,my Listbox won't update doing a listBox1.UpdateLayout();
Any clue/help on how to start implementing this one?
Thank you very much.
UPDATED
namespace pestotora
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
UIload(true);
WebLoad();
}
public ObservableCollection<PestotoraPost> Posts { get; set; }
public class PestotoraPost
{
public string ID { get; set; }
public string Date { get; set; }
public string Name { get; set; }
public string Message { get; set; }
}
void WebLoad()
{
WebClient pestotora = new WebClient();
pestotora.DownloadStringCompleted += new DownloadStringCompletedEventHandler(pestotora_DownloadStringCompleted);
pestotora.DownloadStringAsync(new Uri("www.domain.com/xml.php"));
}
void UIload(bool Splash)
{
if (Splash == true)
{
ApplicationBar.IsVisible = false;
}
else
{
ApplicationBar.IsVisible = true;
}
}
void pestotora_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//XDocument doc = XDocument.Parse(e.Result);
XElement doc = XElement.Parse(e.Result);
/* listBox1.ItemsSource = from results in doc.Descendants("Data")
select new PestotoraPost
{
ID = results.Element("DataID").Value,
Date = results.Element("DataDate").Value,
Name=results.Element("DataName").Value,
Message=results.Element("DataMessage").Value
}; */
var list = from results in doc.Descendants("Data")
select new PestotoraPost
{
ID = results.Element("DataID").Value,
Date = results.Element("DataDate").Value,
Name = results.Element("DataName").Value,
Message = results.Element("DataMessage").Value
};
Posts = new ObservableCollection<PestotoraPost>(list);
foreach (var post in list)
{
Posts.Add(post);
}
UIload(false);
}
private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
{
//stckPost.Visibility = System.Windows.Visibility.Visible;
}
private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/Post.xaml", UriKind.Relative));
}
private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
{
listBox1.UpdateLayout();
//listBox1.ScrollIntoView(listBox1.Items[0]);
WebLoad();
}
}
}
1. If you use MVVM pattern: In viewModel implement INotifyPropertyChanged and declare:
private ObservableCollection<PestotoraPost> _posts;
public ObservableCollection<PestotoraPost> Posts
{
get{return _posts;}
set
{
_posts = value;
RaisePropertyChanged("Posts");
}
}
in xaml write:
<ListBox Name="listbox1" ItemsSource="{Binding Posts}"/>
in pestotora_DownloadStringCompleted method:
var list = from results in doc.Descendants("Data")
select new PestotoraPost
{
ID = results.Element("DataID").Value,
Date = results.Element("DataDate").Value,
Name=results.Element("DataName").Value,
Message=results.Element("DataMessage").Value
};
Posts = new ObservableCollection<PestotoraPosts>(list);
2. If you run everything in a code-behind just declare
public ObservableCollection<PestotoraPosts> Posts {get;set;}
And in Page constructor init collection:
Posts = new ObservableCollection<PestotoraPosts>();
Xaml will have the same declaration.
And in pestotora_DownloadStringCompleted method:
var list = from results in doc.Descendants("Data")
select new PestotoraPost
{
ID = results.Element("DataID").Value,
Date = results.Element("DataDate").Value,
Name=results.Element("DataName").Value,
Message=results.Element("DataMessage").Value
};
foreach(var post in list)
{
Posts.Add(post);
}
What have we done?
In xaml we set a databinding . Now listBox1 will get data from Post collection.
Then we created new collection and notyfied listBox1 to update it's view. (in first vatiant).
In second variant we populated collection and as it was observable it notifyed a list box.

Resources