public async Task <bool> UploadImageToServer(ImageUpload imageUpload) { if (imageUpload != null) { try { string filepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), imageUpload.FileName); NSData data = NSData.FromStream(App.FileHelper.GetStreamFromImageFile(filepath)); var image = UIImage.LoadFromData(data); PheidiParams pp = new PheidiParams(); pp.Add("NOSEQ", imageUpload.QueryFieldValue); pp.Add("FIELD", imageUpload.Field); bool success = await UploadImageToServer(image, imageUpload.FileName, filepath, pp, false); if (success) { if (File.Exists(filepath)) { File.Delete(filepath); } } return(success); } catch (Exception e) { Debug.WriteLine(e.Message); await DatabaseHelper.Database.DeleteItemAsync(imageUpload); } } return(false); }
public async Task <bool> UploadImageToServer(ImageUpload imageUpload) { if (imageUpload == null) { return(false); } string filepath = imageUpload.FilePath; var image = BitmapFactory.DecodeStream(App.FileHelper.GetStreamFromImageFile(filepath)); if (image == null) { return(false); } PheidiParams pp = new PheidiParams(); pp.Add("NOSEQ", imageUpload.QueryFieldValue); pp.Add("FIELD", imageUpload.Field); return(await UploadImageToServer(image, imageUpload.FileName, pp, false)); }
static public void ImageImport(UIImagePickerControllerSourceType sourceType, NSUrlRequest request) { var imagePicker = new UIImagePickerController { SourceType = sourceType }; imagePicker.FinishedPickingMedia += (send, ev) => { var image = (UIImage)ev.Info.ObjectForKey(new NSString("UIImagePickerControllerOriginalImage")); var filename = String.Format("Pic_{0}.png", NoSeqGenerator.Generate()); var filepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), filename); using (NSData imageData = image.AsPNG()) { Byte[] byteArray = new Byte[imageData.Length]; System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, byteArray, 0, Convert.ToInt32(imageData.Length)); App.FileHelper.SaveImage(filepath, byteArray); } UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null); var imageEditor = new PheidiTOCropViewController(image); imageEditor.OnEditFinished(() => { var param = request.Body.ToString().Split('&'); PheidiParams pp = new PheidiParams(); int index = 0; for (int i = 0; i < param.Length; i++) { if (param[i].Contains("pheidiparams")) { pp.Load(WebUtility.UrlDecode(param[i])); index = i; } } image = imageEditor.FinalImage; if (image != null) { using (NSData imageData = image.AsJPEG()) { Byte[] byteArray = new Byte[imageData.Length]; System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, byteArray, 0, Convert.ToInt32(imageData.Length)); App.FileHelper.SaveImage(filepath, byteArray); } if (App.NetworkManager.GetHostServerState() == NetworkState.Reachable && (App.NetworkManager.GetNetworkState() == NetworkState.ReachableViaWiFiNetwork || App.WifiOnlyEnabled == false)) { Task.Run(async() => { await UploadImageToServer(image, filename, filepath, pp); }); } else { string title = ""; string message = ""; if (App.NetworkManager.GetHostServerState() == NetworkState.NotReachable) { title = AppResources.Alerte_ImageUploadHoteInacessibleTitle; message = AppResources.Alerte_ImageUploadHoteInacessibleMessage; } else if (App.WifiOnlyEnabled) { title = AppResources.Alerte_ImageUploadPasDeWifiTitle; message = AppResources.Alerte_ImageUploadPasDeWifiMessage; } App.NotificationManager.DisplayAlert(message, title, "OK", () => { }); Task.Run(async() => { var iu = new ImageUpload() { FileName = filename, FilePath = filepath, Field = pp["FIELD"], QueryFieldValue = pp["NOSEQ"], User = App.UserNoseq, ServerNoseq = App.CurrentServer.Noseq }; await DatabaseHelper.Database.SaveItemAsync(iu); }); } } }); UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(imageEditor, true, () => { }); }; imagePicker.Canceled += (send, ev2) => { UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null); }; UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(imagePicker, true, null); }
static public async Task <bool> UploadImageToServer(UIImage image, string filename, string filepath, PheidiParams pheidiparams, bool displayAlert = true) { string p = ""; var dic = new Dictionary <string, string>(); var uploadId = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds.ToString("F0"); var url = App.CurrentServer.Address + "/upload.ashx"; var parameters = new Dictionary <string, string> { { "uploadID", uploadId } }; var timeout = new TimeSpan(0, 0, 240); var handler = new HttpClientHandler() { CookieContainer = App.CookieManager.GetAllCookies() }; using (var httpClient = new HttpClient(handler, true)) { MultipartFormDataContent content = new MultipartFormDataContent(); content.Add(new StringContent(uploadId), "uploadID"); Stream imageStream = new MemoryStream(); imageStream = image.AsPNG().AsStream(); var streamContent = new StreamContent(imageStream); content.Add(streamContent, "Filedata", filename); content.Add(new StringContent(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), "ModDate"); content.Add(new StringContent(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), "CrDate"); content.Add(new StringContent("image"), "callType"); content.Add(new StringContent(pheidiparams["NOSEQ"]), "qfv"); content.Add(new StringContent("2"), "BD"); HttpResponseMessage response = null; try { HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post, url); httpRequest.Content = content; httpRequest.Headers.Add("User-Agent", "Ipheidi " + Device.RuntimePlatform); httpRequest.Headers.Add("UserHostAddress", App.NetworkManager.GetIPAddress()); Debug.WriteLine(await httpRequest.Content.ReadAsStringAsync()); httpClient.Timeout = timeout; response = await httpClient.SendAsync(httpRequest); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(App.ಠ_ಠ); Debug.WriteLine(ex.Message + "\n\n" + ex.ToString()); App.NetworkManager.CheckHostServerState(); }; if (response != null) { if (response.StatusCode == HttpStatusCode.OK) { string responseContent = response.Content.ReadAsStringAsync().Result; Debug.WriteLine("Reponse:" + responseContent); if (responseContent == "1") { dic = new Dictionary <string, string>(); dic.Add("FIELD", pheidiparams["FIELD"]); dic.Add("NOSEQ", pheidiparams["NOSEQ"]); dic.Add("VALUE", "'" + uploadId + "'"); foreach (var d in dic) { p += d.Key + "**:**" + d.Value + "**,**"; } parameters = new Dictionary <string, string> { { "pheidiaction", "UpdateFieldValue" }, { "pheidiparams", p } }; response = null; response = await PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 30)); if (response != null) { if (response.StatusCode == HttpStatusCode.OK) { responseContent = response.Content.ReadAsStringAsync().Result; Debug.WriteLine("Reponse:" + responseContent); if (!responseContent.StartsWith("erreur", StringComparison.OrdinalIgnoreCase)) { if (displayAlert) { App.NotificationManager.DisplayAlert(AppResources.Alerte_EnvoiePhotoCompleteMessage, "Pheidi", "OK", () => { }); try { DeleteImageInDirectory(filename); } catch (Exception e) { Debug.WriteLine(e.Message); } } return(true); } } } } } } } return(false); }
public string ExecuteAction(string pheidiparams, string objectAction) { PheidiParams pp = new PheidiParams(); pp.Load(pheidiparams); if (pp.ContainsKey("FILECHOOSER")) { PheidiWebChromeClient.FileChooserPheidiParams = pp; } else if (objectAction == "geofenceAutoCreate") { try { string answer = ""; string p = ""; var dic = new Dictionary <string, string>(); dic.Add("OTHERFIELD", pp["FIELD"]); dic.Add("NOSEQ", pp["NOSEQ"]); dic.Add("FIELD", "geofence"); foreach (var d in dic) { p += d.Key + "**:**" + d.Value + "**,**"; } var parameters = new Dictionary <string, string> { { "pheidiaction", "GetFieldValueFromOtherField" }, { "pheidiparams", p } }; HttpResponseMessage response = PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 30)).Result; if (response != null) { if (response.StatusCode == HttpStatusCode.OK) { string responseContent = response.Content.ReadAsStringAsync().Result; System.Diagnostics.Debug.WriteLine("Reponse:" + responseContent); try { answer = PheidiNetworkManager.GetFields(responseContent)[0][dic["FIELD"]] as string; } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); } } } if (string.IsNullOrEmpty(answer)) { string val = ""; if (pp.ContainsKey("VALUE")) { val = pp["VALUE"]; } bool EndOfProcess = false; string message = "Voulez-vous associez \"" + val + "\" comme étant le lieux actuel?"; var a = new System.Action(() => { try { var location = App.LocationService.GetLocation(); string noseq = ""; bool createNewGeo = true; if (location != null) { var potentialGeofences = App.GeofenceManager.GetOverlappingGeofences(location.Latitude, location.Longitude); if (potentialGeofences.Any(g => g.Name.ToLower() == val.ToLower())) { var geo = potentialGeofences.First(g => g.Name.ToLower() == val.ToLower()); noseq = geo.NoSeq; createNewGeo = false; } } if (createNewGeo) { var geo = new Geofence() { Latitude = location.Latitude, Longitude = location.Longitude, NotificationEnabled = true, User = App.UserNoseq, ServerNoseq = App.CurrentServer.Noseq, NotificationDelay = ApplicationConst.DefaultGeofenceTriggerTime, Name = val, Radius = ApplicationConst.DefaultGeofenceRadius }; geo.SetIsInside(true); if (pp.ContainsKey("ENTERACTIONNAME")) { geo.EnterActionName = pp["ENTERACTIONNAME"]; } if (pp.ContainsKey("EXITACTIONNOSEQ")) { geo.ExitActionName = pp["EXITACTIONNAME"]; } geo.Radius = ApplicationConst.DefaultGeofenceRadius; App.GeofenceManager.AddGeofence(geo); noseq = geo.NoSeq; } pheidiparams = PheidiParams.InsertValueInString(pheidiparams, "IPheidi_Params", noseq); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); } finally { EndOfProcess = true; } }); App.NotificationManager.DisplayAlert(message, "", "Oui", "Non", a, () => { EndOfProcess = true; }); while (!EndOfProcess) { Task.Delay(500); } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); } } return(pheidiparams); }
public static bool canInitWithRequest(NSUrlRequest request) { BrowserPage.CheckWebSession(); if (request.Body != null) { if (request.Body.ToString().Contains("Logoff")) { Device.BeginInvokeOnMainThread(App.Instance.Logout); } else if (request.Url.ToString().Contains("localisation")) { return(!request.Body.ToString().Contains("Longitude") && !request.Body.ToString().Contains("Latitude") && request.Body.ToString().Contains("pheidiparams")); } else if (request.Url.ToString().Contains("geofenceAutoCreate")) { return(!CurrentlyProcessingRequestLocaly); } } if (request.Url.ToString().Contains("ImportImage")) { try { var param = request.Body.ToString().Split('&'); PheidiParams pp = new PheidiParams(); int index = 0; for (int i = 0; i < param.Length; i++) { if (param[i].Contains("pheidiparams")) { pp.Load(WebUtility.UrlDecode(param[i])); index = i; } } Task.Run(async() => { string answer = ""; if (pp.ContainsKey("FIELDVALUE")) { if (!string.IsNullOrEmpty(pp["FIELDVALUE"])) { var dic = new Dictionary <string, string>(); dic.Add("OTHERFIELD", pp["FIELD"]); dic.Add("NOSEQ", pp["NOSEQ"]); dic.Add("FIELD", pp["FIELD"]); string p = ""; foreach (var d in dic) { p += d.Key + "**:**" + d.Value + "**,**"; } var parameters = new Dictionary <string, string> { { "pheidiaction", "GetFieldValueFromOtherField" }, { "pheidiparams", p } }; HttpResponseMessage response = await PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 30)); if (response != null) { if (response.StatusCode == HttpStatusCode.OK) { string responseContent = response.Content.ReadAsStringAsync().Result; Debug.WriteLine("Reponse:" + responseContent); try { answer = PheidiNetworkManager.GetFields(responseContent)[0][dic["FIELD"]] as string; } catch (Exception e) { Debug.WriteLine(e.Message); } } } } } if (!string.IsNullOrEmpty(answer)) { var p = ""; var dic = new Dictionary <string, string>(); dic.Add("FIELD", pp["FIELD"]); dic.Add("NOSEQ", pp["NOSEQ"]); dic.Add("VALUE", "NULL"); foreach (var d in dic) { p += d.Key + "**:**" + d.Value + "**,**"; } var parameters = new Dictionary <string, string> { { "pheidiaction", "UpdateFieldValue" }, { "pheidiparams", p } }; var response = await PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 30)); if (response != null) { if (response.StatusCode == HttpStatusCode.OK) { var responseContent = response.Content.ReadAsStringAsync().Result; Debug.WriteLine("Reponse:" + responseContent); } } } else { Device.BeginInvokeOnMainThread(() => { UIAlertController actionSheetAlert = UIAlertController.Create(null, null, UIAlertControllerStyle.ActionSheet); // Add Actions var a1 = UIAlertAction.Create(AppResources.CameraFileChooser, UIAlertActionStyle.Default, (action) => ImageHelper.ImageImport(UIImagePickerControllerSourceType.Camera, request)); a1.SetValueForKey(new UIImage("camera.png"), new NSString("image")); actionSheetAlert.AddAction(a1); var a2 = UIAlertAction.Create(AppResources.GaleriePhotoFileChooser, UIAlertActionStyle.Default, (action) => ImageHelper.ImageImport(UIImagePickerControllerSourceType.PhotoLibrary, request)); a2.SetValueForKey(new UIImage("sort.png"), new NSString("image")); actionSheetAlert.AddAction(a2); actionSheetAlert.AddAction(UIAlertAction.Create(AppResources.AnnulerBouton, UIAlertActionStyle.Cancel, null)); UIViewController rootView = UIApplication.SharedApplication.KeyWindow.RootViewController; //Setting du popoverPresentationController, obligatoire pour iPad if (Device.Idiom == TargetIdiom.Tablet) { actionSheetAlert.PopoverPresentationController.SourceView = rootView.View; var width = rootView.View.Bounds.Width; var height = rootView.View.Bounds.Height; Debug.WriteLine("Width: " + width + ", Height: " + height); actionSheetAlert.PopoverPresentationController.SourceRect = new CGRect(width / 4, 3 * height / 4, width / 2, height / 4); actionSheetAlert.PopoverPresentationController.WillReposition += (sender, e) => { //Changement d'orientation if (width > height != rootView.View.Bounds.Width > rootView.View.Bounds.Height) { actionSheetAlert.DismissViewController(false, null); } }; actionSheetAlert.PopoverPresentationController.PermittedArrowDirections = 0; } rootView.PresentViewController(actionSheetAlert, true, null); }); } }); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } return(false); }
public static new NSUrlRequest GetCanonicalRequest(NSUrlRequest request) { string data = ""; if (request.Body != null) { string[] param = request.Body.ToString().Split('&'); if (request.Url.ToString().Contains("localisation")) { for (int i = 0; i < param.Length; i++) { if (param[i].Contains("pheidiparams")) { var location = App.LocationService.GetLocation(); string values = ""; string str = ""; if (location != null) { values = "Longitude%2A%2A%3A%2A%2A" + location.Longitude + "%2A%2A%2C%2A%2ALatitude%2A%2A%3A%2A%2A" + location.Latitude; } else { values = "Longitude%2A%2A%3A%2A%2Anull%2A%2A%2C%2A%2ALatitude%2A%2A%3A%2A%2Anull"; } string[] keyValue = param[i].Split('='); str = keyValue[1] == "null" ? keyValue[0] + "=" + values : param[i] + values; param[i] = str; } } foreach (var str in param) { data += data.Length > 0 ? "&" + str : str; } return(GenerateRequest(request, data)); } else if (request.Url.ToString().Contains("geofenceAutoCreate")) { param = request.Body.ToString().Split('&'); PheidiParams pp = new PheidiParams(); int index = 0; for (int i = 0; i < param.Length; i++) { if (param[i].Contains("pheidiparams")) { pp.Load(WebUtility.UrlDecode(param[i])); index = i; } } if (!CurrentlyProcessingRequestLocaly) { CurrentlyProcessingRequestLocaly = true; try { Task.Run(async() => { string answer = ""; string p = ""; var dic = new Dictionary <string, string>(); dic.Add("OTHERFIELD", pp["FIELD"]); dic.Add("NOSEQ", pp["NOSEQ"]); dic.Add("FIELD", "geofence"); foreach (var d in dic) { p += d.Key + "**:**" + d.Value + "**,**"; } var parameters = new Dictionary <string, string> { { "pheidiaction", "GetFieldValueFromOtherField" }, { "pheidiparams", p } }; HttpResponseMessage response = await PheidiNetworkManager.SendHttpRequestAsync(parameters, new TimeSpan(0, 0, 30)); if (response != null) { if (response.StatusCode == HttpStatusCode.OK) { string responseContent = response.Content.ReadAsStringAsync().Result; Debug.WriteLine("Reponse:" + responseContent); try { answer = PheidiNetworkManager.GetFields(responseContent)[0][dic["FIELD"]] as string; } catch (Exception e) { Debug.WriteLine(e.Message); } } } if (string.IsNullOrEmpty(answer)) { string val = ""; if (pp.ContainsKey("VALUE")) { val = pp["VALUE"]; } string message = string.Format(AppResources.Alerte_VoulezVousAssociezXCommelieuMessage, val); var a = new System.Action(() => { try { var location = App.LocationService.GetLocation(); string noseq = ""; string pheidiParams = ""; data = ""; bool createNewGeo = true; if (location != null) { var potentialGeofences = App.GeofenceManager.GetOverlappingGeofences(location.Latitude, location.Longitude); if (potentialGeofences.Any(g => g.Name.ToLower() == val.ToLower())) { var geo = potentialGeofences.First(g => g.Name.ToLower() == val.ToLower()); noseq = geo.NoSeq; createNewGeo = false; } } if (createNewGeo) { var geo = new Geofence() { Latitude = location.Latitude, Longitude = location.Longitude, NotificationEnabled = true, User = App.UserNoseq, ServerNoseq = App.CurrentServer.Domain, NotificationDelay = ApplicationConst.DefaultGeofenceTriggerTime, Radius = ApplicationConst.DefaultGeofenceRadius, Name = val }; geo.SetIsInside(true); if (pp.ContainsKey("ENTERACTIONNAME")) { geo.EnterActionName = pp["ENTERACTIONNAME"]; } if (pp.ContainsKey("EXITACTIONNAME")) { geo.ExitActionName = pp["EXITACTIONNAME"]; } geo.Radius = ApplicationConst.DefaultGeofenceRadius; App.GeofenceManager.AddGeofence(geo); noseq = geo.NoSeq; } pheidiParams = PheidiParams.InsertValueInString(param[index], "IPheidi_Params", noseq); for (int i = 0; i < param.Length; i++) { string str = i != index ? param[i] : pheidiParams; data += data.Length > 0 ? "&" + str : str; } Debug.WriteLine(data); SendRequest(GenerateRequest(request, data)); Task.Delay(100); } catch (Exception e) { Debug.WriteLine(e.Message); } finally { CurrentlyProcessingRequestLocaly = false; } }); App.NotificationManager.DisplayAlert(message, "", AppResources.Oui, AppResources.Non, a, () => { CurrentlyProcessingRequestLocaly = false; }); } else { CurrentlyProcessingRequestLocaly = false; } }); } catch (Exception e) { Debug.WriteLine(e.Message); CurrentlyProcessingRequestLocaly = false; } return(null); } } } return(request); }