WP7 - accessing UI thread? - multithreading

How do I access the UI thread of a WP7 application?
I am using the following code, if it helps.
private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
{
AcquireNews(l => { listBox1.Items.Add(l[0]); });
// Here is where I get an exception saying "Invalid cross-thread access."
}
void AcquireNews(Action<List<object>> callback)
{
var r = HttpWebRequest.Create("http://www.google.com") as HttpWebRequest;
r.BeginGetResponse(result =>
{
var response = r.EndGetResponse(result);
List<object> l = new List<object>();
var s = response.GetResponseStream();
var buffer = new byte[s.Length];
s.Read(buffer, 0, (int)s.Length);
l.Add(System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length));
callback(l);
},
null);
}

You can use the Dispatcher for this.
Dispatcher.BeginInvoke( () => { /* Your UI Code - ie Callback() or listbox.items.add */ } );

Related

How to stop Azure Message Session Handler from timing out when listening for messages?

Below is my synchronous implementation of the IMessageSessionHandler interface. One problem I have is that when there are no messages in the queue the InitializeReceiverSync method will repeatedly run until the web job ungracefully times out in Azure, resulting in a failure. On the other hand if there are messages in the queue to be read, once they are read, the session closes and the program exits.
What is the best way to exit the method if there are no messages in the queue?
public void ReceiveMessagesFromAzure()
{
int i = 0;
while (i < 4)
{
var QueueName = ConfigurationManager.AppSettings["QueueName"];
var connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
CancellationTokenSource cts = new CancellationTokenSource();
InitializeReceiverSync(connectionString, QueueName, cts.Token);
i++;
}
}
public void InitializeReceiverSync(string connectionString, string queueName, CancellationToken ct)
{
var receiverFactory = MessagingFactory.CreateFromConnectionString(connectionString);
ct.Register(() => receiverFactory.Close());
var client = receiverFactory.CreateQueueClient(queueName, ReceiveMode.PeekLock);
client.RegisterSessionHandler(
typeof(SessionHandler),
new SessionHandlerOptions
{
MessageWaitTimeout = TimeSpan.FromSeconds(5),
MaxConcurrentSessions = 1,
AutoComplete = false
});
}
class SessionHandler : IMessageSessionHandler
{
AzureRepository ar = new AzureRepository([queueName], [connectionString]);
void IMessageSessionHandler.OnMessage(MessageSession session, BrokeredMessage message)
{
ar.ProcessMessage(message);
}
void IMessageSessionHandler.OnCloseSession(MessageSession session)
{
Console.WriteLine("Session closed");
Environment.Exit(0);
}
void IMessageSessionHandler.OnSessionLost(Exception exception)
{
Console.WriteLine(exception.Message);
Console.WriteLine("Press any key to exit");
}
}

Need help to deal with Photo for Xamarin forms

I am using xamarin forms. I want to pick photo from gallery for my iphone app and want to save it in Azure DB. Is there any solution available for xamarin forms. Or Is there any plugin available to deal with Photo, Document, or Audio. Any help is appreciated.
Using dependency service you can take or pick photos from Android / iPhone :-
Please refer to code below and try to implement the similar code:-
This is the interface in PCL:-
public interface IGalleryProvider
{
Task<List<AttachmentMediaFile>> PickPhotoAsync();
Task<List<AttachmentMediaFile>> PickAudioAsync();
Task<List<AttachmentMediaFile>> PickDocumentAsync();
Task<AttachmentMediaFile> PickProfilePhotoAsync();
Task SaveToGalleryAsync(AttachmentMediaFile file);
}
Below is the code using which you can pick or take photos from iPhone only:-
using AssetsLibrary;
using AVFoundation;
using ELCImagePicker;
using Foundation;
using MediaPlayer;
using MobileCoreServices;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UIKit;
[assembly: Xamarin.Forms.Dependency(typeof(GalleryProvider))]
namespace SanketSample.MobileApp.Sample.iOS.Common
{
public class GalleryProvider : IGalleryProvider
{
private TaskCompletionSource<List<AttachmentMediaFile>> _audioPickedTask;
public async Task<List<AttachmentMediaFile>> PickAudioAsync()
{
_audioPickedTask = new TaskCompletionSource<List<AttachmentMediaFile>>();
var picker = new MPMediaPickerController();
ShowViewController(picker);
picker.ItemsPicked += OnAudioPicked;
picker.DidCancel += OnCancel;
var media = await _audioPickedTask.Task;
return media;
}
private void OnCancel(object sender, EventArgs e)
{
var picker = sender as MPMediaPickerController;
picker.DidCancel -= OnCancel;
picker.DismissViewController(true, null);
_audioPickedTask.TrySetResult(new List<AttachmentMediaFile>());
}
private void OnAudioPicked(object sender, ItemsPickedEventArgs e)
{
var media = new List<AttachmentMediaFile>();
var picker = sender as MPMediaPickerController;
picker.ItemsPicked -= OnAudioPicked;
picker.DismissViewController(true, null);
if (e.MediaItemCollection.Items != null)
{
foreach (var item in e.MediaItemCollection.Items)
{
//var vm1 = (new ViewModelLocator()).AttachmentsVM.SelectedAttachments.Add();
if (!item.IsCloudItem)
{
try
{
//var error = new NSError();
//var asset = new AVUrlAsset(item.AssetURL);
//var exporter = new AVAssetExportSession(asset, item.Title);
//exporter.OutputFileType = "com.apple.m4a-audio";
//AVAssetExportSession session = new AVAssetExportSession(asset, "");
//var reader = new AVAssetReader(asset, out error);
//var settings = new NSDictionary();
//Func<byte[]> bytesGetter = e.MediaItemCollection
//TODO item.Title, item.Title SSSanket,
//var _asset = AVAsset.FromUrl(NSUrl.FromFilename(item.AssetURL.ToString()));
//var _exportSession = new AVAssetExportSession(_asset, AVAssetExportSession.PresetPassthrough);
//_exportSession.OutputFileType = AVFileType.Aiff;
// media.Add(new AttachmentMediaFile(item.AssetURL.AbsoluteString, AttachmentMediaFileType.Audio, null , item.Title));
}
catch (Exception ex)
{
// throw ;
}
}
}
}
_audioPickedTask.TrySetResult(media);
}
public async Task<List<AttachmentMediaFile>> PickDocumentAsync()
{
var task = new TaskCompletionSource<List<AttachmentMediaFile>>();
var allowedUTIs = new string[]
{
UTType.UTF8PlainText,
UTType.PlainText,
UTType.RTF,
UTType.Text,
UTType.PDF,
"com.microsoft.word.doc",
"com.microsoft.excel.xls"
};
var pickerMenu = new UIDocumentMenuViewController(allowedUTIs, UIDocumentPickerMode.Open);
pickerMenu.DidPickDocumentPicker += (sender, args) =>
{
args.DocumentPicker.DidPickDocument += (sndr, pArgs) =>
{
var securityEnabled = pArgs.Url.StartAccessingSecurityScopedResource();
NSError err;
var fileCoordinator = new NSFileCoordinator();
var docs = new List<AttachmentMediaFile>();
// Read bytes.
fileCoordinator.CoordinateRead(pArgs.Url, 0, out err, (NSUrl newUrl) =>
{
NSData data = NSData.FromUrl(newUrl);
docs.Add(new AttachmentMediaFile(pArgs.Url.AbsoluteString, AttachmentMediaFileType.Doc, data.ToArray(),null));
task.TrySetResult(docs);
});
};
ShowViewController(args.DocumentPicker);
};
ShowViewController(pickerMenu);
return await task.Task;
}
public async Task<List<AttachmentMediaFile>> PickPhotoAsync()
{
var media = new List<AttachmentMediaFile>();
var picker = ELCImagePickerViewController.Instance;
picker.MaximumImagesCount = 15;
ShowViewController(picker);
await picker.Completion.ContinueWith(result =>
{
picker.BeginInvokeOnMainThread(() =>
{
picker.DismissViewController(true, null);
if (!result.IsCanceled && result.Exception == null)
{
var imageEditor = new ImageEditor();
var items = result.Result as List<AssetResult>;
foreach (var item in items)
{
var bbytes= imageEditor.ResizeImage(item.Image, 1024, 1024);
media.Add(new AttachmentMediaFile(item.Path, AttachmentMediaFileType.Photo, bbytes, item.Name));
}
}
});
});
return media;
}
public async Task<AttachmentMediaFile> PickProfilePhotoAsync()
{
AttachmentMediaFile selectMediaFile = null;
var picker = ELCImagePickerViewController.Instance;
picker.MaximumImagesCount = 1;
ShowViewController(picker);
await picker.Completion.ContinueWith(result =>
{
picker.BeginInvokeOnMainThread(() =>
{
picker.DismissViewController(true, null);
if (!result.IsCanceled && result.Exception == null)
{
var imageEditor = new ImageEditor();
var items = result.Result as List<AssetResult>;
foreach (var item in items)
{
var bbytes = imageEditor.ResizeImage(item.Image, 1024, 1024);
selectMediaFile = new AttachmentMediaFile(item.Path, AttachmentMediaFileType.Photo, bbytes, item.Name);
}
}
});
});
return selectMediaFile;
}
public async Task SaveToGalleryAsync(AttachmentMediaFile file)
{
var bytes = file.GetBytes();
var originalImage = ImageEditor.ImageFromByteArray(bytes);
var library = new ALAssetsLibrary();
var orientation = (ALAssetOrientation)originalImage.Orientation;
var nsUrl = await library.WriteImageToSavedPhotosAlbumAsync(originalImage.CGImage, orientation);
}
private void ShowViewController(UIViewController controller)
{
var topController = UIApplication.SharedApplication.KeyWindow.RootViewController;
while (topController.PresentedViewController != null)
{
topController = topController.PresentedViewController;
}
topController.PresentViewController(controller, true, null);
}
}
}
Below are useful classes :-
public class AttachmentMediaFile
{
private readonly Func<byte[]> _bytesGetter;
public string LocalPath { get; private set; }
public string Name { get; private set; }
public AttachmentMediaFileType Type { get; private set; }
public AttachmentMediaFile(string localPath, AttachmentMediaFileType type, byte[] bytesGetter, string name = null)
{
LocalPath = localPath;
Type = type;
_bytesGetter = () =>
{
return bytesGetter;
};
if (string.IsNullOrEmpty(name))
{
Name = FileNameHelper.PrepareName(localPath);
}
else
{
Name = name;
}
}
public byte[] GetBytes()
{
return _bytesGetter();
}
}
public enum AttachmentMediaFileType
{
Photo = 0,
Audio = 1,
Doc = 2,
Video = 3,
}
public static class FileNameHelper
{
private const string Prefix = "IMG";
public static string PrepareName(string localPath)
{
var name = string.Empty;
if (!string.IsNullOrEmpty(localPath))
{
name = localPath.Split('/').Last();
}
return name;
}
public static string GenerateUniqueFileName(Extension extension)
{
var format = ".jpg";
var fileName = string.Concat(Prefix, '_', DateTime.UtcNow.Ticks, format);
return fileName;
}
public enum Extension
{
JPG
}
}
Now if you want to store your data to Azure Server Table so you are already using Azure mobile service client SDK similarly you need Blob nuget from Azure using which you can save your photos by making blob objects to Azure server :-
use blob helper nuget from manage nuget package install Microsoft.WindowsAzure.Storage.Auth;
Microsoft.WindowsAzure.Storage.Blob;
this and try to implement the code similarly I given bellow:-
using Acr.UserDialogs;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using SanketSample.MobileApp.sample.Business.Azure;
using SanketSample.MobileApp.sample.Business.Interfaces;
using SanketSample.MobileApp.sample.Models;
using SanketSample.MobileApp.sample.Models.AzureTables;
using SanketSample.MobileApp.sample.Models.Media;
using SanketSample.MobileApp.sample.Utils;
using Xamarin.Forms;
namespace SanketSample.MobileApp.Sanket.Common.Media
{
public class BlobHelper
{
private const string ContainerName = "attachments";
private Dictionary<string, TaskCompletionSource<bool>> _tasks;
private IHttpService _httpservice { get; set; }
#region Singleton Implementation
private static readonly Lazy<BlobHelper> lazyInstance = new Lazy<BlobHelper>(() => new BlobHelper(), true);
private BlobHelper()
{
_tasks = new Dictionary<string, TaskCompletionSource<bool>>();
}
public static BlobHelper Instance
{
get { return lazyInstance.Value; }`enter code here`
}
#endregion Singleton Implementation
public async Task UploadAttachments(IList<AttachmentFile> attachments, long associatedRecordId, string category)
{
foreach (var attachment in attachments)
{
await UploadAttachment(attachment, associatedRecordId, category);
}
}
public async Task UploadAttachment(AttachmentFile attachment, long associatedRecordId, string category)
{
try
{
CommonHelper commonHelper = new CommonHelper();
attachment.ContainerName = ContainerName;
attachment.AssociatedRecordId = associatedRecordId;
//attachment.RecordId = commonHelper.GenerateRecordId();
if (attachment.FileExtension == null)
{
attachment.FileExtension = ConvertType(attachment.MediaFile);
}
attachment.Category = category;
var taskCompletionSource = new TaskCompletionSource<bool>();
if (!_tasks.ContainsKey(attachment.Name))
{ _tasks.Add(attachment.Name, taskCompletionSource); }
else
{
_tasks[attachment.Name] = taskCompletionSource;
}
// _tasks.Add(attachment.Name, taskCompletionSource);
var attachmentsTableOnline = AzureServiceProvider.Instance.GetRemoteTable<AttachmentFile>();
if (CheckInternetConnection.IsConnected())
{
await attachmentsTableOnline.InsertAsync(attachment);
}
var attachmentsTableOffline = AzureServiceProvider.Instance.GetLocalTable<AttachmentFile>();
await attachmentsTableOffline.InsertAsync(attachment);
if (!string.IsNullOrEmpty(attachment.SasQueryString))
{
var credentials = new StorageCredentials(attachment.SasQueryString);
var imageUri = new Uri(attachment.Uri);
var container = new CloudBlobContainer(new Uri(string.Format("https://{0}/{1}",
imageUri.Host, attachment.ContainerName)), credentials);
var blobFromSASCredential = container.GetBlockBlobReference(attachment.Name);
try
{
var bytes = attachment.MediaFile.GetBytes();
await blobFromSASCredential.UploadFromByteArrayAsync(bytes, 0, bytes.Length);
if (CheckInternetConnection.IsConnected())
{
await attachmentsTableOnline.UpdateAsync(attachment);
}
await attachmentsTableOffline.UpdateAsync(attachment);
taskCompletionSource.TrySetResult(true);
}
catch (Microsoft.WindowsAzure.Storage.StorageException ex)
{
// Throws from UploadFromByteArrayAsync, but image uploaded.
System.Diagnostics.Debug.WriteLine($"BlobHelper: {ex}");
taskCompletionSource.TrySetResult(true);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"BlobHelper: {ex}");
taskCompletionSource.TrySetResult(false);
}
}
}
catch (Exception ca)
{
//throw ca;
}
}
/// <summary>
/// Downloads Blob Data boject and returns the Byts[] data
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public async Task<byte[]> DownloadAttachment(AttachmentFile file)
{
byte[] bytes = null;
var fileContainer = file.Uri.Replace(file.Name, string.Empty);
var container = new CloudBlobContainer(new Uri(fileContainer));
var blob = container.GetBlockBlobReference(file.Name);
using (var stream = new MemoryStream())
{
var isExist = await blob.ExistsAsync();
if (isExist)
{
await blob.DownloadToStreamAsync(stream);
bytes = stream.ToArray();
}
}
return bytes;
}
/// <summary>
/// Updates the Attachments Byts in the Azure Local Tables.
/// </summary>
/// <param name="AttachmentFileRecordId">Attachments Byte[] Data.</param>
/// <returns></returns>
public async Task<byte[]> DownloadAttachmentFileDetails(long? AttachmentFileRecordId, IHttpService service)
{
_httpservice = service;
try
{
ResponseWrapper<AttachmentFileDetail> result = new ResponseWrapper<AttachmentFileDetail>();
if (AttachmentFileRecordId != null)
{
var request = Constants.API_BASE_URL + string.Format(Constants.API_ATTACHMENTS_PARAMETERS, AttachmentFileRecordId);
var response = await _httpservice.SendRequestAsync(HttpMethod.Get, request);
result.Status = response.Status;
if (response.IsSuccess)
{
result.Result = JsonConvert.DeserializeObject<AttachmentFileDetail>(response.Result);
if (result.Result == null)
{
result.Status = System.Net.HttpStatusCode.InternalServerError;
}
else
{
var output = result.Result;
var data = new List<AttachmentFileDetail>() { output };
await AzureServiceProvider.Instance.DatabaseService.InsertDataToLocalDB<AttachmentFileDetail>(data);
return result.Result.FileByteArray;
}
}
}
}
catch (Exception ex)
{
////throw ex;
}
finally
{
}
return null;
}
private string ConvertType(AttachmentMediaFile file)
{
switch (file.Type)
{
case AttachmentMediaFileType.Doc:
return "doc";
case AttachmentMediaFileType.Audio:
return "mp3";
}
return "jpeg";
}
}
}
media plugin on github
works pretty well for me.

ReceiveAsync from UDP socket

I want to create a UDP socket to receive data from Local Endpoint.
I do not know the Remote Port where data come from, that's why I thought I would use ReceiveAsync. But it does not work.
I give my code right now and any advice would be useful:
public class Program
{
ManualResetEvent clientDone;
Socket socket;
public static void Main(string[] args)
{
clientDone = new ManualResetEvent(false);
socket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint localIPEP = new IPEndPoint( IPAddress.Any, 0);
socket.Bind( (EndPoint) localIPEP);
while (listening)
Receive();
}
string Receive()
{
string response;
byte[] recvData = new byte[24];
if (socket != null)
{
SocketAsyncEventArgs ae = new SocketAsyncEventArgs();
ae.SetBuffer(recvData, 0, recvData.Length);
// callback
ae.Completed += new EventHandler<SocketAsyncEventArgs>(delegate (object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response.Trim('\0');
}
else
{
response = e.SocketError.ToString();
}
switch (e.LastOperation)
{
case SocketAsyncOperation.Receive:
ProcessReceivedData(e);
break;
}
clientDone.Set();
});
clientDone.Reset();
Console.WriteLine("Local EndPoint: " + ((IPEndPoint)socket.LocalEndPoint).ToString());
socket.ReceiveAsync(ae);
clientDone.WaitOne(1000);
}
return response;
}
}
P.S. I work on Linux .Net Core

Easy way to handle AcceptMessageSessionAsync and ReceiveAsync

Attempting to jump into the Windows Server ServiceBus 1.1 code-base along with adopting the new TPL async methods. But I could not find an easy way to just spin up N number of handlers for message sessions (might have 100 or so concurrent sessions). So it would be great to get some feedback on the following code, any suggestions on an easier way would be great... note tried to keep code sample simple for the questions purpose.
///example usage
SubscriptionClient subClient = SubscriptionClient.Create(TopicName, SubscriptionName);
subClient.HandleSessions(5, msg =>
{
Console.WriteLine(string.Format("Processing recived Message: SessionId = {0}, Body = {1}",
msg.SessionId,
msg.GetBody<string>()));
msg.Complete();
});
public static class SubscriptionClientExtensions
{
public static void HandleSessions (this SubscriptionClient sc, Int32 numberOfSessions, Action<BrokeredMessage> handler)
{
Action<Task<MessageSession>> sessionAction = null;
Action<Task<BrokeredMessage>> msgHandler = null;
sessionAction = new Action<Task<MessageSession>>(tMS =>
{
if (tMS.IsFaulted) // session timed out - repeat
{
sc.AcceptMessageSessionAsync().ContinueWith(sessionAction);
return;
}
MessageSession msgSession = null;
try
{
msgSession = tMS.Result;
}
catch (Exception)
{
return; // task cancelation exception
}
msgHandler = new Action<Task<BrokeredMessage>>(taskBM =>
{
if (taskBM.IsFaulted)
return;
BrokeredMessage bMsg = null;
try
{
bMsg = taskBM.Result;
}
catch (Exception)
{
return; // task cancelation exception
}
if (bMsg == null)
{
sc.AcceptMessageSessionAsync().ContinueWith(sessionAction); // session is dead
return;
}
handler(bMsg); // client code to handle the message
msgSession.ReceiveAsync(TimeSpan.FromSeconds(5)).ContinueWith(msgHandler); // repeat
});
msgSession.ReceiveAsync(TimeSpan.FromSeconds(5)).ContinueWith(msgHandler); // start listening
});
for (Int32 nIndex = 0; nIndex < numberOfSessions; nIndex++)
{
sc.AcceptMessageSessionAsync().ContinueWith(sessionAction);
}
}
}

Show splash screen and hide after finish web request

When my app start I want to show splash screen and create httpwebrequest and when request is finish hide splash screen and show main page.
This is my splash screen:
private void ShowPopup()
{
this.popup = new Popup();
this.popup.Child = new PopupSplash();
this.popup.IsOpen = true;
StartLoadingData();
}
private void StartLoadingData()
{
backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
backgroundWorker.RunWorkerAsync();
}
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Dispatcher.BeginInvoke(() =>
{
this.popup.IsOpen = false;
}
);
}
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
using (var db = new ListDataContext(ListDataContext.DBConnectionString))
{
if (!db.DatabaseExists())
{
db.CreateDatabase();
}
}
Thread.Sleep(4000);
}
and this is my httpwebrequest:
private void main_WebResponseAvailableEventHandler(object sender, string response, string url)
{
SearchResult result = new SearchResult(response, url);
PhoneApplicationService.Current.State["result"] = result;
this.NavigationService.Navigate(new Uri("/SearchPivotPage.xaml", UriKind.Relative));
}
private void HandleWebResponse(IAsyncResult asyncResult)
{
WebRequestState state = (WebRequestState)asyncResult.AsyncState;
HttpWebRequest request = state.Request;
string url = request.RequestUri.ToString();
state.Response = (HttpWebResponse)request.EndGetResponse(asyncResult);
if (state.Response != null)
{
StreamReader reader = new StreamReader(state.Response.GetResponseStream());
StringBuilder sb = new StringBuilder();
while (!reader.EndOfStream)
sb.Append(reader.ReadLine());
string text = sb.ToString();
Dispatcher.BeginInvoke(() =>
{
if (WebResponseAvailable != null)
{
WebResponseAvailable(this, text, url);
}
});
}
}
in constructor MainPage()
....
ShowPopup();
HttpWebRequest movieRequest = (HttpWebRequest)WebRequest.Create(url);
WebRequestState state = new WebRequestState();
state.Request = movieRequest;
movieRequest.BeginGetResponse(new AsyncCallback(HandleWebResponse), state);
WebResponseAvailable += main_WebResponseAvailableEventHandler;
....
Is there a way how can I do what I want? Or that both are in other thread this isnĀ“t possible?
You could create a fake splashScreen by adding a new SplashScreenPage.xaml page instead of SpalshScreen.jpg file. If you delete SplashScreen.jpg file the first page that should be loaded (from App.xaml) will be SplashScreenPage.xaml and there you can perform any operation like webrequest as you pointed out above. Once webrequest ends then do navigate to mainPage.xaml and then call RemoveBackEntry method in order to make MainPage.xaml the first page entry in the BackStack.
Regards,

Resources