Telerik RadDataBoundListBox Reset - windows-phone-8

how can i reset or delete old data in Telerik RadDataBoundListBox
Json parse and display in RadDataBoundListBox
RadDataBoundListBox load old data every time, if i click button to load new data i want to delete or reset old data becouse every time displaying old data
public void getMainData()
{
string mainUrlData = "http://www.mydomain.com/app.json";
WebClient wc = new WebClient();
wc.DownloadStringCompleted += wc_DownloadStringCompleted;
wc.DownloadStringAsync(new Uri(mainUrlData));
}
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
string result = e.Result.ToString();
JsonConvert.PopulateObject(result, PopulateData);
NewsList.ItemsSource = PopulateData;
}
}

Little late, hope this helps..
With MVVMLight
Use HttpClient:
public async Task<ObservableCollection<T>> GetAll()
{
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(jsonMediaType));
//if (useToken)
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
var json = await client.GetStringAsync(String.Format("{0}{1}{2}", apiUrl, addressSuffix, apiKey)).ConfigureAwait(false);
Debug.WriteLine(json);
JObject o = JObject.Parse(json);
Debug.WriteLine(o);
return await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<ObservableCollection<T>>(o[moduleName].ToString()));
}
ItemSource:
private ObservableCollection<Ticket> _myTickets;
public ObservableCollection<Ticket> MyTickets
{
get
{
return _myTickets;
}
set
{
_myTickets = value;
RaisePropertyChanged(() => MyTickets);
}
}
Telerik RadBoundListBox:
<telerikPrimitives:RadDataBoundListBox
x:Name="radDataBoundListBox"
ItemsSource="{Binding TicketList}"
ItemTemplate="{StaticResource ListBoxItemTemplate}"
ItemContainerStyle="{StaticResource ItemContainerStyle}"
SelectedItem="{Binding SelectedTicket, Mode=TwoWay}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Height="750"
ScrollViewer.VerticalScrollBarVisibility="Auto"
UseOptimizedManipulationRouting="False"
EmptyContent="Laden..."
IsPullToRefreshEnabled="True">
<i:Interaction.Triggers>
<i:EventTrigger EventName="RefreshRequested">
<cmd:EventToCommand
Command="{Binding RefreshRequested}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</telerikPrimitives:RadDataBoundListBox>
Refresh Command:
private RelayCommand _refreshCommand;
public RelayCommand RefreshRequested
{
get
{
return _refreshCommand
?? (_refreshCommand = new RelayCommand(
() =>
{
ExecuteRefreshCommand();
}));
}
}
public async void ExecuteRefreshCommand()
{
var tickets = await _dataService.GetAll();
if (tickets != null)
{
_ticketList.Clear();
foreach (var ticket in tickets)
{
_ticketList.Add(ticket);
Debug.WriteLine(ticket.name);
}
Messenger.Default.Send(new HandleViewMessage() { StopPullToRefresh = true });
RaisePropertyChanged(() => TicketList);
}
}

Related

How to work with large images on Blazor/ Web

my question is how to manage really large images on the web. Im using blazor, I need to send and recive Images of 100mb or more, And im using webshockets to send btwin the web and the server that send images. Im using base64 but its also slow.
this is how i send and i recive an image
public class WebshocketConections
{
public Uri _Uri = new Uri("ws://xxx.xxx.xxx.xxx:YYYY");
ClientWebSocket _cliente;
CancellationTokenSource cts = new();
public delegate void CheckNewMessage(string a);
public event CheckNewMessage? onMessage;
public WebshocketConections(ClientWebSocket client, Uri uri)
{
_cliente = client;
_Uri = uri;
}
public async Task Connect()
{
cts.CancelAfter(TimeSpan.FromSeconds(100));
await _cliente.ConnectAsync(_Uri, cts.Token);
await Echo(_cliente);
}
public async Task SendString(string message)
{
ArraySegment<byte> byteToSend = await Task.Run(() => { return new ArraySegment<byte>(Encoding.UTF8.GetBytes(message)); });
await _cliente.SendAsync(byteToSend, WebSocketMessageType.Text, true, cts.Token);
}
public async Task SendImage(byte[] Base64)
{
ArraySegment<byte> byteToSend = await Task.Run(() => { return new ArraySegment<byte>(Encoding.UTF8.GetBytes("img" + Convert.ToBase64String(Base64))); });
await _cliente.SendAsync(byteToSend, WebSocketMessageType.Binary, true, cts.Token);
}
public async Task<ClientWebSocket> GetClient()
{
return _cliente;
}
private async Task Echo(ClientWebSocket client)
{
var buffer = new byte[1024 * 1000000];
var receiveResult = await client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!receiveResult.CloseStatus.HasValue)
{
onMessage(Encoding.UTF8.GetString(buffer, 0, receiveResult.Count));
await client.SendAsync(
new ArraySegment<byte>(buffer, 0, receiveResult.Count),
receiveResult.MessageType,
receiveResult.EndOfMessage,
CancellationToken.None);
receiveResult = await client.ReceiveAsync(
new ArraySegment<byte>(buffer),
CancellationToken.None);
}
await client.CloseAsync(
receiveResult.CloseStatus.Value,
receiveResult.CloseStatusDescription,
CancellationToken.None);
}
}

BackgroundTask in Lifecycle Events works but not automatically

I am trying to update the data in my secondary tile using a background task. It gets updated when I select my background task from the lifecycle events dropdown. However it doesn't work automatically. Does it mean that my SystemTrigger is not getting fired? Please help.
Here is my code:
public static void CheckIfBackgroundTaskExist()
{
if (BackgroundTaskRegistration.AllTasks.Count < 1)
{
RegisterBackgroundTask();
}
}
public static void RegisterBackgroundTask()
{
BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
builder.Name = "SecondaryTileUpdate";
builder.TaskEntryPoint = "BackgroundTaskLiveTile.SecondaryTileUpdater";
//IBackgroundTrigger trigger = new MaintenanceTrigger(15, false);
IBackgroundTrigger trigger = new SystemTrigger(SystemTriggerType.TimeZoneChange, false);
builder.SetTrigger(trigger);
IBackgroundTaskRegistration task = builder.Register();
}
public async void Run(IBackgroundTaskInstance taskInstance)
{
//HERE: request a deferral
var deferral = taskInstance.GetDeferral();
var list = await SecondaryTile.FindAllAsync();
foreach (SecondaryTile liveTile in list)
{
HttpClient client = new HttpClient();
var response = await client.GetAsync(url, HttpCompletionOption.ResponseContentRead);
if (!response.IsSuccessStatusCode)
{
//
}
if (response != null)
{
string content = await response.Content.ReadAsStringAsync();
try
{
MyProperty= JsonConvert.DeserializeObject<MyClass>(content);
}
catch
{
//MessageBox.Show("Unable to retrieve data");
}
}
// Update Secondary Tiles
if (liveTile.TileId == "MySecondaryTileId")
{
await UpdateMyTile();
}
}
}

How cancel Async Call in Windows Phone?

I have a list wich is loaded with elements each time the user make a research...These elements contain an Icon which is dowloaded with an async method GetByteArrayAsync of the HttpClient object. I have an issue when the user make a second research while the icon of the first list are still downloading.Because the list of elements is changing while Icon downloads are processing on each element of the first list. So my guess is that I need to cancel these requests each time the user proceed to a new research...Ive readen some stuuf on Task.run and CancellationTokenSource but I can't find really helpful example for my case so here is my code...Hope you can help me with that ...Thank you
public static async Task<byte[]> DownloadElementFile(BdeskElement bdeskElement)
{
//create and send the request
DataRequest requesteur = new DataRequest();
byte[] encryptedByte = await requesteur.GetBytesAsync(dataRequestParam);
return encryptedByte;
}
public async Task<Byte[]> GetBytesAsync(DataRequestParam datarequesparam)
{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(datarequesparam.AuthentificationLogin, datarequesparam.AuthentificationPassword, "bt0d0000") };
HttpClient httpClient = new HttpClient(handler);
try
{
byte[] BytesReceived = await httpClient.GetByteArrayAsync(datarequesparam.TargetUri);
if (BytesReceived.Length > 0)
{
return BytesReceived;
}
else
{
return null;
}
}
catch (WebException)
{
throw new MyException(MyExceptionsMessages.Webexception);
}
}
EDIT
public async Task<Byte[]> GetBytesAsync(DataRequestParam datarequesparam)
{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(datarequesparam.AuthentificationLogin, datarequesparam.AuthentificationPassword, "bt0d0000") };
HttpClient httpClient = new HttpClient(handler);
try
{
cts = new CancellationTokenSource();
HttpResponseMessage reponse = await httpClient.GetAsync(datarequesparam.TargetUri,cts.Token);
if (reponse.StatusCode == HttpStatusCode.OK)
{
byte[] BytesReceived = reponse.Content.ReadAsByteArrayAsync().Result;
if (BytesReceived.Length > 0)
{
return BytesReceived;
}
else
{
return null;
}
}
else
{
return null;
}
}
catch (WebException)
{
throw new MyException(MyExceptionsMessages.Webexception);
}
catch(OperationCanceledException)
{
throw new OperationCanceledException();
}
EDIT2
I need to cancel this funntion when the user make a new research and the list "listBoxGetDocsLibs" changed.
private async void LoadIconDocLibs()
{
foreach (var doclib in listBoxGetDocsLibs)//ERROR HERE COLLECTION HAS CHANGED
{
doclib.Icon = new BitmapImage();
try
{
byte[] Icon = await ServerFunctions.GetDocLibsIcon(doclib);
if (Icon != null)
{
{
var ms = new MemoryStream(Icon);
BitmapImage photo = new BitmapImage();
photo.DecodePixelHeight = 64;
photo.DecodePixelWidth = 92;
photo.SetSource(ms);
doclib.Icon = photo;
}
}
}
catch(OperationCanceledException)
{
}
}
}
First you need to define CancellationTokenSource:
private System.Threading.CancellationTokenSource cts;
place above code somewhere, where you can access it with your Button or other method.
Unfortunately GetByteArrayAsync lacks Cancelling - so it cannot be used with cts.Token, but maybe you can accomplish your task using GetAsync - which supports Cancelling:
ctsDownload = new System.Threading.CancellationTokenSource();
HttpResponseMessage response = await httpClient.GetAsync(requestUri, cts.Token);
Then you can get your content from response.
And when you want to Cancel your Task it can look like this:
private void cancelBtn_Click(object sender, RoutedEventArgs e)
{
if (this.cts != null)
this.cts.Cancel();
}
When you Cancel task an Exception will be thrown.
If you want to cancel your own async Task, a good example you can find at Stephen Cleary blog.
EDIT - you can also build your own method (for example with HttpWebRequest) which will support Cancelling:
For this purpose you will have to extend HttpWebRequest (under WP it lacks GetResponseAsync):
// create a static class in your namespace
public static class Extensions
{
public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest webRequest)
{
TaskCompletionSource<HttpWebResponse> taskComplete = new TaskCompletionSource<HttpWebResponse>();
webRequest.BeginGetResponse(
asyncResponse =>
{
try
{
HttpWebRequest responseRequest = (HttpWebRequest)asyncResponse.AsyncState;
HttpWebResponse someResponse = (HttpWebResponse)responseRequest.EndGetResponse(asyncResponse);
taskComplete.TrySetResult(someResponse);
}
catch (WebException webExc)
{
HttpWebResponse failedResponse = (HttpWebResponse)webExc.Response;
taskComplete.TrySetResult(failedResponse);
}
catch (Exception exc) { taskComplete.SetException(exc); }
}, webRequest);
return taskComplete.Task;
}
}
Then your method can look like this:
public async Task<Byte[]> GetBytesAsync(DataRequestParam datarequesparam, CancellationToken ct)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(datarequesparam.TargetUri);
request.Method = "GET";
request.Credentials = new NetworkCredential(datarequesparam.AuthentificationLogin, datarequesparam.AuthentificationPassword, "bt0d0000");
request.AllowReadStreamBuffering = false;
try
{
if (request != null)
{
using (HttpWebResponse response = await request.GetResponseAsync())
using (Stream mystr = response.GetResponseStream())
using (MemoryStream output = new MemoryStream())
{
const int BUFFER_SIZE = 10 * 1024;
byte[] buf = new byte[BUFFER_SIZE];
int bytesread = 0;
while ((bytesread = await mystr.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
{
output.Write(buf, 0, bytesread);
ct.ThrowIfCancellationRequested();
}
return output.ToArray();
}
}
else return null;
}
catch (WebException)
{
throw new MyException(MyExceptionsMessages.Webexception);
}
}
You can freely change Buffer Size which will affect how often Cancellation will be checked.
I haven't tried this but I think it should work.

Waiting and Return a result with DownloadStringAsync WP8

I do a webrequest with DownloadStringAsync() but I need to return the result only when the DownloadStringCompleted event has been called. After the downloadasync-method, I need to wait for the result and then I could return it in a string property. So I implemented a while(Result == "") but I don't know what to do there. I already tried Thread.sleep(500) but it seems the download never gets completed. And the code remains in the while forever.
string Result = "";
public String Query(DataRequestParam dataRequestParam)
{
try
{
WebClient web = new WebClient();
if (!string.IsNullOrEmpty(dataRequestParam.AuthentificationLogin))
{
System.Net.NetworkCredential account = new NetworkCredential(dataRequestParam.AuthentificationLogin, dataRequestParam.AuthentificationPassword);
web.Credentials = account;
}
web.DownloadStringCompleted += OnDownloadStringCompleted;
web.DownloadStringAsync(dataRequestParam.TargetUri);
while (Result == "")
{
//What am i supposed to do here ?
}
return Result;
}
catch(WebException we)
{
MessageBox.Show(we.Message);
return null;
}
}
private void OnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
//Error treating
}
else
{
Result = e.Result;
}
}
UI CODE
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.NavigationMode != NavigationMode.Back)
{
ServerFunctions.SetUserProfil(User.UserLogin,User.UserPassword);
this.listBoxGetDocsLibs.Clear();
List<BdeskDocLib> list = new List<BdeskDocLib>();
try
{
//HERE THE START OF THE DOWNLOAD
ServerFunctions.GetDocLibs(true);
}
catch (Exception ex)
{
//error
}
foreach (BdeskDocLib docLib in list)
{
this.listBoxGetDocsLibs.Add(docLib);
}
}
}
the ServerFunction static class
public static List<BdeskDocLib> GetDocLibs(bool onlyDocLibPerso)
{
string xmlContent = GetXml(URL_GETDOCLIBS);
List<BdeskDocLib> result = BdeskDocLib.GetListFromXml(xmlContent, onlyDocLibPerso);
return result;
}
private static String GetXml(string partialUrl)
{
string url = GenerateUrl(partialUrl);
DataRequestParam dataRequestParam = new DataRequestParam();
dataRequestParam.TargetUri = new Uri(url);
dataRequestParam.UserAgent = "BSynchro";
dataRequestParam.AuthentificationLogin = userLogin;
dataRequestParam.AuthentificationPassword = userPwd;
//HERE I START THE QUERY method
// NEED QUERY RETURNS A STRING or Task<String>
DataRequest requesteur = new DataRequest();
xmlResult=requesteur.Query(dataRequestParam);
if (CheckErrorConnexion(xmlResult) == false)
{
throw new Exception("Erreur du login ou mot de passe");
}
return xmlResult;
}
There is nothing good in blocking main UI (unless you really need to). But if you want to wait for your result you can make some use of async-await and TaskCompletitionSource - you can find more about on this blog and how to use TCS in this answer:
public static Task<string> myDownloadString(DataRequestParam dataRequestParam)
{
var tcs = new TaskCompletionSource<string>();
var web = new WebClient();
if (!string.IsNullOrEmpty(dataRequestParam.AuthentificationLogin))
{
System.Net.NetworkCredential account = new NetworkCredential(dataRequestParam.AuthentificationLogin, dataRequestParam.AuthentificationPassword);
web.Credentials = account;
}
web.DownloadStringCompleted += (s, e) =>
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(e.Result);
};
web.DownloadStringAsync(dataRequestParam.TargetUri);
return tcs.Task;
}
public async Task<string> Query(DataRequestParam dataRequestParam)
{
string Result = "";
try
{
Result = await myDownloadString(dataRequestParam);
}
catch (WebException we)
{
MessageBox.Show(we.Message);
return null;
}
return Result;
}
(I've not tried this code, there maight be some mistakes, but it should work)
Basing on this code you can also extend your WebClient with awaitable version of download string.

I am getting error in LoginAsync method during wp8 App development for sky drive

I am developing a windows phone 8 application to access sky drive. I am getting following error when I call LoginAsync() method-
An exception of type 'Microsoft.Live.LiveAuthException' occurred in mscorlib.ni.dll but was not handled in user code
using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Live;
namespace SkyDriveApp
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
LiveConnectClient client;
public MainPage()
{
InitializeComponent();
}
public async void Auth()
{
string clientId = "My_client_id";
LiveAuthClient auth = new LiveAuthClient(clientId);
// var result = await auth.InitializeAsync(new[] { "wl.basic", "wl.signin", "wl.skydrive_update" });
var result = await auth.LoginAsync(new[] { "wl.basic", "wl.signin", "wl.skydrive_update" });
if (result.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(result.Session);
tbMessage.Text = "Connected!";
}
}
private void btnLogin_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
Auth();
}
}
}
I see that you are using provided login buton, try this:
In xaml:
<live:SignInButton Name="skyBtn" ClientId="your client ID" Scopes="wl.signin wl.skydrive wl.skydrive_update" Branding="Skydrive" TextType="Login"/>
In code behind:
private void skyBtn_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
session = e.Session;
client = new LiveConnectClient(session);
tbMessage.Text = "Connected!";
}
else tbMessage.Text = "Not Connected!";
if (e.Error != null)
{
tbMessage.Text = "Not Connected!";
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(e.Error.Message);
});
}
}