Xamarin iOS Perform Segue with Scandit - c#

I am using a barcode scanner to grab a barcode and then I want to segue to my next screen right after that barcode is grabbed and I use that to find some specific data. The scanning works fine, and when the barcode is scanned The method DidScanBarcode is hit and runs through, is in this method that I try and perform my segue but the app either freezes or crashes without ever performing the segue and the method PrepareForSegue is never hit after the PerformSegue is run. Any thoughts?
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
using RedLasterPrototype;
using System.Threading.Tasks;
using CoreGraphics;
using ZXing.Mobile;
using ScanditSDK;
namespace Prototype
{
partial class ScanViewController : UIViewController
{
public static ProductElement ScannedProduct { get; set; }
ScanditDelegate scanditDelegate;
public static string appKey = "xxxxx";
public ScanViewController(IntPtr handle) : base (handle)
{
}
public async override void ViewDidLoad()
{
var picker = new ScanditSDK.SIBarcodePicker (appKey);
scanditDelegate = new ScanditDelegate ();
picker.OverlayController.Delegate = scanditDelegate;
PresentViewController (picker, true, null);
picker.StartScanning ();
}
public static ProductElement GetScannedData(string upc)
{
var _service = new RestService ();
var data = _service.GetDataFromUpc (upc);
if (data != null)
{
return data;
}
return null;
}
public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
{
base.PrepareForSegue (segue, sender);
if (segue.Identifier == "SegueToProductPage")
{
var destination = (ScannedProductViewController)segue.DestinationViewController;
destination.product = ScannedProduct;
}
}
public class ScanditDelegate : SIOverlayControllerDelegate
{
public override void DidScanBarcode (SIOverlayController overlayController, NSDictionary barcode) {
// perform actions after a barcode was scanned
Console.WriteLine ("barcode scanned: {0}, '{1}'", barcode["symbology"], barcode["barcode"]);
var code = barcode ["barcode"].ToString();
if(code != null)
{
ScannedProduct = GetScannedData (code);
var x = new ScanViewController (this.Handle);
x.PerformSegue ("SegueToProductPage", this);
}
}
public override void DidCancel (SIOverlayController overlayController, NSDictionary status) {
// perform actions after cancel was pressed
}
public override void DidManualSearch (SIOverlayController overlayController, string text) {
// perform actions after search was used
}
}
}
}

Related

How to make possible to listen to another App song/audio

I am leaning Xamarin,
I have build a quick app that read audio effect file (mp3/wav).
My problem :
When I start the App while I was listened music ( spotify/deezer ) the musique stops because the app has started.
So, I would like to be able to listen to music ( spotify/deezer ) and use my app.
My audio C# class in Android looks like this :
public class MyAudioOutput : IAudioServiceOutput
{
public void GetAudioSetting()
{
var audioManager = (Android.Media.AudioManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.AudioService);
audioManager.Mode = Mode.Normal;
audioManager.SpeakerphoneOn = true;
}
}
My Audio C# classe in IOS looks like this :
public class MyAudioOutput : IAudioServiceOutput
{
public void GetAudioSetting()
{
var session = AVAudioSession.SharedInstance();
session.OverrideOutputAudioPort(AVAudioSessionPortOverride.Speaker, out NSError error);
session.SetCategory(AVAudioSessionCategory.Playback);
session.SetActive(true);
}
}
My interface in Xamarin Forms shared :
public interface IAudioServiceOutput
{
void GetAudioSetting();
}
In my Xamarin forms cs file , I use the function this way :
ISimpleAudioPlayer AudioPlayerGood;
void InitMyAudio()
{
string filenamegood = "Question.Good_Answer.mp3";
using (Stream streamGood = GetType().GetTypeInfo().Assembly.GetManifestResourceStream(filenamegood))
{
AudioPlayerGood = CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
AudioPlayerGood.Load(streamGood);
}
}
void OnPlayAnswerSong(bool goodanswer)
{
if (goodanswer == true)
{
AudioPlayerGood.Play();
}
else if (goodanswer == false)
{
AudioPlayerWrong.Play();
}
}
Thanks for you help
For this, you can refer to the following thread:Pause background service in Xamarin.Forms
The implementation on android platform is as follows:
[assembly: Dependency(typeof(StopMusicService))]
namespace TTSDemo.Droid
{
public class StopMusicService : IControl
{
AudioManager audioMan;
AudioManager.IOnAudioFocusChangeListener listener;
public void StopBackgroundMusic()
{
audioMan = (AudioManager)Android.App.Application.Context.GetSystemService(Context.AudioService);
listener = new MyAudioListener(this);
var ret = audioMan.RequestAudioFocus(listener, Stream.Music, AudioFocus.Gain);
}
}
internal class MyAudioListener :Java.Lang.Object, AudioManager.IOnAudioFocusChangeListener
{
private StopMusicService stopMusicService;
public MyAudioListener(StopMusicService stopMusicService)
{
this.stopMusicService = stopMusicService;
}
public void OnAudioFocusChange([GeneratedEnum] AudioFocus focusChange)
{
// throw new NotImplementedException();
}
}
}
And you can also check the updated part code by Nieminen included in above link.

Xamarin WebView download doesn't work for Mp4Upload

I have a small Xamarin form app that I want to use to download files from mp4Upload. This is done by loading the mp4Upload url onto a WebView and then programmatically clicking the download button using WebView.EvaluateJavascriptAsync().
The problem is that it doesn't trigger a download.
public class AndroidWebView : WebViewRenderer
{
public AndroidWebView(Context ctx) : base(ctx)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.Settings.UserAgentString = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/20100101 Firefox/4.0";
}
Control.Download += DownloadEvent;
}
private void DownloadEvent(object sender, Android.Webkit.DownloadEventArgs e)
{
string url = e.Url;
DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(url));
request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, "CPPPrimer");
DownloadManager dm = (DownloadManager)Android.App.Application.Context.GetSystemService("download");
dm.Enqueue(request);
Toast.MakeText(Android.App.Application.Context, e.Url, ToastLength.Long).Show();
}
}
I've tested the above code with a github url to download a random .gitignore file which works fine.
The mp4Upload link also works in chrome if I manually click download as well as working on winforms using cefsharp using ChromiumWebBrowser.ExecuteScriptAsync() to programmatically click download.
Does anyone know how to fix this issue?
It's not as simple as it looks, especially for downloads that open in a _blank target. This is the code I used in one of my projects:
Setup your webview to support downloads:
using Xamarin.Forms;
using Android.Webkit;
using Android.Content;
using System.Threading.Tasks;
using Xamarin.Forms.Platform.Android;
// In your android webview renderer
protected override void OnElementChanged(ElementChangedEventArgs<XamWebView> e)
{
base.OnElementChanged(e);
if (this.Control != null)
{
var xamWebView = (AppWebView)e.NewElement;
this.AllowFileDownloads(this.Control, xamWebView);
}
}
private void AllowFileDownloads(DroidWebView webView, AppWebView customWebView)
{
webView.Settings.SetSupportMultipleWindows(false);
var downloadListener = new WebViewDownloadListener(this.Context);
webView.SetDownloadListener(downloadListener);
}
Use this as your webview download listener
using System;
using Android.App;
using Android.Widget;
using Android.Webkit;
using Android.Content;
using Xamarin.Essentials;
public class WebViewDownloadListener : Java.Lang.Object, IDownloadListener
{
private Context AppContext { get; }
public event Action<string> OnDownloadStarted;
private DownloadManager DownloadManager => DownloadManager.FromContext(this.AppContext);
public WebViewDownloadListener(Context appContext)
{
this.AppContext = appContext;
this.AppContext.RegisterReceiver(new OnDownloadCompleteOpenFileInDefaultApp(), new IntentFilter(DownloadManager.ActionDownloadCom
}
public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
{
this.OnDownloadStarted?.Invoke(url);
var downloadRequest = BuildDownloadRequest(url, userAgent, contentDisposition, mimetype);
AppErrorHandler.ExecuteSafely(async () =>
{
if (ShouldAskPermissionToSaveFile)
{
var permission = await Permissions.RequestAsync<Permissions.StorageWrite>();
if (permission == PermissionStatus.Granted)
this.EnqueueDownloadRequest(downloadRequest);
}
else
this.EnqueueDownloadRequest(downloadRequest);
});
}
private static bool ShouldAskPermissionToSaveFile => Android.OS.Build.VERSION.SdkInt <= Android.OS.BuildVersionCodes.P;
private void EnqueueDownloadRequest(DownloadManager.Request downloadRequest)
{
this.DownloadManager.Enqueue(downloadRequest);
Toast.MakeText(this.AppContext, "Downloading File", ToastLength.Long).Show();
}
private static DownloadManager.Request BuildDownloadRequest(string url, string userAgent, string contentDisposition, string mimetype)
{
var request = new DownloadManager.Request(Android.Net.Uri.Parse(url));
request.SetMimeType(mimetype);
request.SetDescription("Downloading file...");
request.AddRequestHeader("User-Agent", userAgent);
request.AddRequestHeader("cookie", CookieManager.Instance.GetCookie(url));
request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
request.SetDestinationInExternalPublicDir(
Android.OS.Environment.DirectoryDownloads,
URLUtil.GuessFileName(url, contentDisposition, mimetype)
);
return request;
}
}
And finally, this as your download broadcast receiver
using Java.IO;
using Android.App;
using Android.Widget;
using Android.Content;
using Android.Database;
using AndroidX.Core.Content;
public class OnDownloadCompleteOpenFileInDefaultApp : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
if (DownloadManager.ActionDownloadComplete.Equals(intent.Action))
{
ICursor cursor = GetDbCursorForDownloadedFile(context, intent);
if (cursor.MoveToFirst())
{
var (downloadStatus, downloadUri, mimeType) = ExtractDataFromCursor(cursor);
if (downloadStatus == (int)DownloadStatus.Successful && downloadUri != null)
{
var fileUri = GetFileUri(context, downloadUri);
var openFileIntent = CreateOpenFileIntent(mimeType, fileUri);
LaunchOpenFileIntent(context, openFileIntent);
}
}
cursor.Close();
}
}
private static ICursor GetDbCursorForDownloadedFile(Context context, Intent intent)
{
var downloadManager = DownloadManager.FromContext(context);
var downloadId = intent.GetLongExtra(DownloadManager.ExtraDownloadId, 0);
var query = new DownloadManager.Query();
query.SetFilterById(downloadId);
var cursor = downloadManager.InvokeQuery(query);
return cursor;
}
private static (int status, string downloadUri, string mimeType) ExtractDataFromCursor(ICursor cursor) =
(
cursor.GetInt(cursor.GetColumnIndex(DownloadManager.ColumnStatus)),
cursor.GetString(cursor.GetColumnIndex(DownloadManager.ColumnLocalUri)),
cursor.GetString(cursor.GetColumnIndex(DownloadManager.ColumnMediaType))
);
private static Android.Net.Uri GetFileUri(Context context, string downloadUri)
{
var fileUri = Android.Net.Uri.Parse(downloadUri);
if (ContentResolver.SchemeFile.Equals(fileUri.Scheme))
{
// FileUri - Convert it to contentUri.
File file = new File(fileUri.Path);
fileUri = FileProvider.GetUriForFile(context, $"{context.PackageName}.fileprovider", file);
}
return fileUri;
}
private static Intent CreateOpenFileIntent(string mimeType, Android.Net.Uri fileUri)
{
Intent openAttachmentIntent = new Intent(Intent.ActionView);
openAttachmentIntent.SetDataAndType(fileUri, mimeType);
openAttachmentIntent.SetFlags(ActivityFlags.GrantReadUriPermission);
return openAttachmentIntent;
}
private static void LaunchOpenFileIntent(Context context, Intent openAttachmentIntent)
{
try
{
context.StartActivity(openAttachmentIntent);
}
catch (ActivityNotFoundException)
{
Toast.MakeText(context, "Could not open file.", ToastLength.Long).Show();
}
}
}

C# Xamarin speech recognition in the background [Android]

Is this possible to make an app what will recognize if I tell eg. "top" or "back" in the background and will start some actions when find if I tell that.
I tested speech recognition when click on button and it shows google voice recognition.
Can I do that without click on button, with recognition in real time in the background?
Yes it is very possible, if you are using google voice recognition on android, what you have to do to get rid of the clicking button is to make your own SpeechRecognizer class and inherit it.
Here is the code I use on my apps :
public class CustomRecognizer : Java.Lang.Object, IRecognitionListener, TextToSpeech.IOnInitListener
{
private SpeechRecognizer _speech;
private Intent _speechIntent;
public string Words;
public CustomRecognizer(Context _context)
{
this._context = _context;
Words = "";
_speech = SpeechRecognizer.CreateSpeechRecognizer(this._context);
_speech.SetRecognitionListener(this);
_speechIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
_speechIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
_speechIntent.PutExtra(RecognizerIntent.ActionRecognizeSpeech, RecognizerIntent.ExtraPreferOffline);
_speechIntent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 1000);
_speechIntent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 1000);
_speechIntent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 1500);
}
void startover()
{
_speech.Destroy();
_speech = SpeechRecognizer.CreateSpeechRecognizer(this._context);
_speech.SetRecognitionListener(this);
_speechIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
_speechIntent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 1000);
_speechIntent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 1000);
_speechIntent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 1500);
StartListening();
}
public void StartListening()
{
_speech.StartListening(_speechIntent);
}
public void StopListening()
{
_speech.StopListening();
}
public void OnBeginningOfSpeech()
{
}
public void OnBufferReceived(byte[] buffer)
{
}
public void OnEndOfSpeech()
{
}
public void OnError([GeneratedEnum] SpeechRecognizerError error)
{
Words = error.ToString();
startover();
}
public void OnEvent(int eventType, Bundle #params)
{
}
public void OnPartialResults(Bundle partialResults)
{
}
public void OnReadyForSpeech(Bundle #params)
{
}
public void OnResults(Bundle results)
{
var matches = results.GetStringArrayList(SpeechRecognizer.ResultsRecognition);
if (matches == null)
Words = "Null";
else
if (matches.Count != 0)
Words = matches[0];
else
Words = "";
//do anything you want for the result
}
startover();
}
public void OnRmsChanged(float rmsdB)
{
}
public void OnInit([GeneratedEnum] OperationResult status)
{
if (status == OperationResult.Error)
txtspeech.SetLanguage(Java.Util.Locale.Default);
}}
To use it on your activity, just create the class and call StartListening()

Conditional EventHandling

I believe I have a design question and I hope to get your input. I made a small program to illustrate my question. Basically, my program consists of a radio system that gets heard on every room in the building. The sound is conditional on the receiving end, depending if the room registers itself to the radio system.
My problem is that the message sent is triggered on every room, even if the room is not registered. I would prefer to do the condition before the message gets sent out, rather then on the receiving end. By doing this, I could save myself unnecessary traffic. Can anyone give me an idea or the correct way to resolve this type of situation?
Just for the record, I would prefer not to have multiple event handlers in the radio, since I don't know how many rooms there will be.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Radio
{
#region Speakers
public interface ISound
{
string sound { get; set; }
}
public abstract class RoomSpeaker : ISound
{
public string sound { get; set; }
}
public class Room1Speaker : RoomSpeaker
{
}
public class Room2Speaker : RoomSpeaker
{
}
public class BuildingSpeaker : RoomSpeaker
{
}
#endregion
#region Rooms
public abstract class Room
{
public Radio radioPlayer;
public string name;
public HashSet<Type> registeredSpeakers = new HashSet<Type>();
public virtual void RoomPlayer(string lyrics)
{
registeredSpeakers.Add(typeof(BuildingSpeaker));
Console.WriteLine(lyrics);
}
}
public class Room1 : Room
{
public Room1(Radio radioPlayer)
{
this.radioPlayer = radioPlayer;
name = "Room1";
registeredSpeakers.Add(typeof(Room1Speaker));
radioPlayer.onRadio += radioPlayer_onRadio;
}
// This is what I don't think I like. It will only do something if it's registered. That's fine.
// But on any radio message out, this room will get called regardless. Should I NOT be doing this? Should I go back to
// making an eventHandler for every room? rather then having one even handler for all the rooms and have a condition on the receiving end.
void radioPlayer_onRadio(object sender, ISound e)
{
if (registeredSpeakers.Contains(e.GetType()))
RoomPlayer(name + e.sound);
}
}
public class Room2 : Room
{
public Room2(Radio radioPlayer)
{
this.radioPlayer = radioPlayer;
name = "Room2";
registeredSpeakers.Add(typeof(Room2Speaker));
radioPlayer.onRadio += radioPlayer_onRadio;
}
void radioPlayer_onRadio(object sender, ISound e)
{
// same problem as in Room1.
if (registeredSpeakers.Contains(e.GetType()))
RoomPlayer(name + e.sound);
}
}
#endregion
public class Radio
{
public event EventHandler<ISound> onRadio;
public void PlayRoom1()
{
onRadio(this, new Room1Speaker() { sound = "Test" });
}
public void PlayRoom2()
{
onRadio(this, new Room2Speaker() { sound = "Test" });
}
public void PlayAllRooms()
{
onRadio(this, new BuildingSpeaker() { sound = "Test All Rooms" });
}
}
class Program
{
static void Main(string[] args)
{
var radio = new Radio();
var room1 = new Room1(radio);
var room2 = new Room2(radio);
radio.PlayRoom1();
radio.PlayRoom2();
radio.PlayAllRooms();
Console.ReadLine();
}
}
}
Okay, what you're looking at is the publish-subscribe pattern (AKA eventbus). In eventbus pattern, you have a class that registers listeners and sends messages. Listeners tell the event bus "I'm listening for an event X". When the eventbus "sends" event X it consults its list of listeners for that event and if they are registered, executes the method that the listener told it to execute.
public class EventBus
{
private Dictionary<Type, List<Action<IEvent>>> actions = new Dictionary<Type, List<Action<IEvent>>>();
public void Listen<T>(Action<IEvent> callback) where T : IEvent
{
if (!actions.ContainsKey(typeof(T)))
{
actions.Add(typeof(T), new List<Action<IEvent>>());
}
actions[typeof(T)].Add(callback);
}
public void ClearCallbacks<T>() where T : IEvent
{
actions[typeof (T)] = null;
}
public void Send<T>(T #event) where T : IEvent
{
if (!actions.ContainsKey(typeof(T)))
{
return;
}
foreach (var action in actions[typeof(T)])
{
action(#event);
}
}
}
public interface IEvent
{
}
Usage:
public static void main () {
var eventBus = new EventBus();
var aRoom = new NoisyRoom(eventBus);
var bRoom = new NoisyRoom(eventBus);
var cRoom = new NoisyRoom(eventBus);
var dRoom = new QuietRoom(eventBus);
eventBus.Send(new NoisyEvent()); //sends to a,b,c room
}
public class EasyListeningEvent : IEvent
{
}
public class QuietRoom
{
public QuietRoom(EventBus eventBus)
{
eventBus.Listen<EasyListeningEvent>(BringTheNaps);
}
private void BringTheNaps(IEvent #event)
{
//its been brought!
}
}
class NoisyEvent : IEvent
{
}
public class NoisyRoom
{
public NoisyRoom(EventBus eventBus)
{
eventBus.Listen<NoisyEvent>(BringTheNoise);
}
private void BringTheNoise(IEvent #event)
{
//its been brought!
}
}
Try something a little more like this:
Edit: Note that this is just a start in the right direction. You can take this a lot further. Basically what you have is a sound source and a sound emitter. Obviously a radio is a sound source, and a speaker is a sound emitter, but something like a room could be both. A radio should not know what a speaker or a room is, it should only know about emitters, and it should only send sounds to them. Based on this, a room should have a collection of emitters (which would probably be speakers), and when a room gets a sound from a radio, it would simply relay that to whatever emitters it has registered. There would also be nothing stopping you from registering speaker directly to a radio. This code should help show how you might implement all of that.
public class Radio
{
private HashTable<string, EventHandler<ISound>> rooms = new ...;
public void RegisterRoom(string room, EventHandler<ISound> onSound)
{
rooms[room] = onSound;
}
public void UnregisterRoom(string room)
{
rooms.Remove(room);
}
public void PlayRoom(string room)
{
EventHandler<ISound> onSound;
if (rooms.TryGetValue(room, out onSound))
{
onSound(this, new BuildingSpeaker() { sound = "Test" });
}
}
public void PlayAllRooms()
{
if (rooms.Count == 0)
{
return;
}
var speaker = new BuildingSpeaker() { sound = "Test All Rooms" };
foreach (var room in rooms)
{
room.Value(this, speaker);
}
}
}

HTTPS call via HttpClient Getting 404 - NOT FOUND

I've been going crazy over this particular problem. What I am trying to do is make an HTTPS Call to the server after a user clicks the sign up button. The server must add the new user to the database and send me back a user key. I've tested the httpClient class with a local LAMP server without HTTPS. Works fine. When I try to connect to the productions server with SSL I GET A 404 - NOT FOUND. I have double checked that the URL, CONTENT and Authorization is formatted well. As a matter of facted I codded it in a console application and it connects to the production server every time. It just does not work with the windows phone emulator or my windows phone. Been monitoring everything with fiddler. I've also used the WebClient class to no avail. PLEASE HELP!
Code below!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JailBird_ProtoType.Models
{
// CLASS USED TO FORMAT OBJECT TO JSON STRING
public class TestUser
{
public string Name { set; get; }
public string Email { get; set; }
public string Password { set; get; }
public List<string> Roles = new List<string>();
}
}
using Microsoft.Phone.Net.NetworkInformation;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace JailBird_ProtoType.Services
{
public class UploadJsonService
{
private BackgroundWorker bw = new BackgroundWorker();
public BackgroundWorker GetBackGroundWorker { get { return bw; } }
private HttpClient client = new HttpClient();
private HttpClient GetClient { get { return client; } }
private HttpResponseMessage response;
public HttpResponseMessage GetResponseMessage { get { return response; } }
// SET THE UPLOAD URL
private string uploadURL;
public string SetUploadURL { set { uploadURL = value; } }
// SET THE STRING DATA UPLOAD VALUE
private string jsonValue ="";
public string SetJsonValue { set { jsonValue = value; } }
private HttpContent httpContent;
public HttpContent GetHttpContent { get { return httpContent; } set { httpContent = value; } }
// SET THE METHOD TYPE UPLOAD VALUE
private string Method = "POST";
public string SetMethod { set { Method = value; } }
// CONSRUCTOR
public UploadJsonService()
{
SetUpClass();
}
public UploadJsonService(string url, string data)
{
SetUploadURL = url;
SetJsonValue = data;
SetUpClass();
}
public UploadJsonService(string url, string method, string data)
{
SetUploadURL = url;
SetJsonValue = data;
SetMethod = method;
SetUpClass();
}
private void SetUpClass()
{
bw.DoWork += new DoWorkEventHandler(DoWork);
httpContent = new StringContent(jsonValue);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
public void StartUpload()
{
try
{
bw.RunWorkerAsync(); // RUN BACKGROUND WORKER
}
catch (Exception) { }
}
public void CancelUpload()
{
// CANCEL ALL WORKER TASKS
try
{
client.Dispose();
httpContent = null;
bw.CancelAsync();
}
catch (Exception) { }
}
public void SetHeader(string header, string value)
{
client.DefaultRequestHeaders.Add(header, value);
}
private async void DoWork(object sender, DoWorkEventArgs e)
{
if (isConnectionReady())
{
try
{
if (Method.ToLower() == "post")
{
response = await client.PostAsync(new Uri(uploadURL, UriKind.Absolute), httpContent);
}
else if (Method.ToLower() == "push")
{
response = await client.PutAsync(new Uri(uploadURL, UriKind.Absolute), httpContent);
}
// DO SOMETHING WITH THE RESPONSE HERE
}
catch (Exception)
{
//UPDATE THE UI THREAD HERE
Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
{
MessageBox.Show("Upload did not complete successfully. Check your connection settings.", "Something Went Wrong", MessageBoxButton.OK);
}));
}
}
else
{
//UPDATE THE UI THREAD HERE
Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
{
MessageBox.Show("Check your phone's connection settings", "No Network Connection", MessageBoxButton.OK);
}));
}
}
// METHOD USED TO CHECK FOR NETWORK CONNECTION
private bool isConnectionReady()
{
bool internet = false;
//Check if network is available
if (DeviceNetworkInformation.IsNetworkAvailable)
{
internet = true;
}
return internet;
}
}
}
// THIS METHOD IS ACTIVATED IN THE SIGNUP BUTTON EVENT HANDLER
public void SendToServer()
{
// string user = JsonConvert.SerializeObject(App.ViewModel.Users[0]); // Get User Information
TestUser me = new TestUser() { Name="testName2", Password="password",Email="mail#mail.com"};
me.Roles.Add("User");
string meString = JsonConvert.SerializeObject(me);
if (App.Settings.Contains("FirstSignUp"))
{
service = new UploadJsonService(ConnectToServer.USER_UPLOAD_URL,"PUT",meString);
}
else
{
service = new UploadJsonService(ConnectToServer.USER_UPLOAD_URL,"POST",meString);
}
service.SetHeader("Authorization", "Basic " + ConnectToServer.Get64BitEncoding(ConnectToServer.SERVER_ADMIN));
service.GetBackGroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerServiceCompleted);
service.StartUpload();
}
private void RunWorkerServiceCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// DO WORK AFTER THE BACKGROUND WORKER COMPLETES
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JailBird_ProtoType.Services
{
// THIS CLASS HOLDS ALL SERVER INFORMATION
// FOR QUICK ACCESS AND CHANGE
public static class ConnectToServer
{
public static string SERVER_ADMIN = "admin:password";
// UPLOAD USER TO DB
public static string USER_UPLOAD_URL = "https://xx.xxx.xx.xxx:443/api/users";
public static string Get64BitEncoding(string key) {
byte[] convert = System.Text.Encoding.UTF8.GetBytes(key);
return System.Convert.ToBase64String(convert);
}
}
}
omitted real server address for security reasons.
Sorry my code is not structured Right. Been changing it around to get this to work.

Categories

Resources