Upload an image to windows azure with xamarin.forms - xamarin.forms

I am trying to make a simple xamarin.forms app for picking an image from the phone gallery and uploading i to the azure storage service.
This is what I have done, but unfortunately I got the error message
"{Microsoft.WindowsAzure.Storage.StorageException: Server failed to authenticate the request."
The pick image from galley code:
private MediaFile mediaFile;
public ImageUpload ()
{
InitializeComponent ();
}
private async void Button_Clicked(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
if(CrossMedia.Current.IsPickPhotoSupported==false)
{
await DisplayAlert("No Pick", "No Available", "ok");
return;
}
this.mediaFile = await CrossMedia.Current.PickPhotoAsync();
if (this.mediaFile == null)
return;
//Show The path in the Xaml
LocalImagPath.Text = this.mediaFile.Path;
//Show the image in the Xaml
MyImageFile.Source = ImageSource.FromStream(this.mediaFile.GetStream);
}//end btnClikcked
private async void uploadPhoto_Clicked(object sender, EventArgs e)
{
try
{
var imageName = await ImageManager.UploadImage(this.mediaFile);
}
catch(Exception ex)
{
ex.StackTrace.ToString();
}
}//end uploadPhoto_Clicked
This is the ImageManger Class:
class ImageManager
{
private static Random random = new Random();
// Uploads a new image to a blob container.
public static async Task<string> UploadImage(MediaFile image)
{
CloudBlobContainer container = GetContainer();
// Creates the container if it does not exist
//await container.CreateIfNotExistsAsync();
// Uses a random name for the new images
var name = Guid.NewGuid().ToString();
// Uploads the image the blob storage
CloudBlockBlob imageBlob = container.GetBlockBlobReference(name);
imageBlob.Properties.ContentType = "image/jpeg";
await imageBlob.UploadFromFileAsync(image.Path);
return name;
}
// Gets a reference to the container for storing the images
private static CloudBlobContainer GetContainer()
{
// Parses the connection string for the WindowS Azure Storage Account
CloudStorageAccount account = CloudStorageAccount.Parse(Configuration.StorageConnectionString);
CloudBlobClient client = account.CreateCloudBlobClient();
// Gets a reference to the images container
CloudBlobContainer container = client.GetContainerReference("bepartphoto");
//Set The Permissions
BlobContainerPermissions blopPerm = new BlobContainerPermissions();
blopPerm.PublicAccess = BlobContainerPublicAccessType.Container;
container.SetPermissionsAsync(blopPerm);
return container;
}//end GetContainer
}//end class

Related

How to capture image from camera and convert the image to base 64 string send to the server in xamarin forms?

I am new to xamarin forms. I implement a simple program where the image is capture from the camera and convert into base64 string and send it to the server like below.
private async void AddNewPhoto(object sender, EventArgs e)
{
MemoryStream memoryStream = new MemoryStream();
img.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.GetStream().CopyTo(memoryStream);
return stream;
});
paths.Enqueue(filePath);
imgPaths.Add(file);
val.Add(img.Source);
// Set StackLayout in XAML to the class field
parent = headerStack1;
parent.Children.Add(img);
}
async void btnSubmitClicked(object sender, EventArgs args)
{
if (paths.Count > 0)
{
string URL1 = "";
string basicDomain1 = AppConstant.ComplaintsUploadImageURL + PhoneNo + "~secretcode-" +
secretCode;
MultipartFormDataContent form1 = new MultipartFormDataContent();
DependencyService.Get<IHudService>().ShowHud("Loading");
List<string> pathItems = new List<string>();
for each (MediaFile ph in imgPaths)
{
var fileName = filePath.Split('\\').LastOrDefault().Split('/').LastOrDefault();
var file = ph;
var upfilebytes = File.ReadAllBytes(file.Path);
var base64 = Convert.ToBase64String(upfilebytes);
var content = new StringContent(base64);
form1.Add(content, "image_64string");
Dictionary<string, string> UploadJson = new Dictionary<string, string>();
UploadJson.Add("image_txt", imgText);
form1.Add(new StringContent(UploadJson["image_txt"]), "image_txt");
form1.Add(new StringContent("jpg"), "image_extension");
var response_ = await this.apiService.PostImageRequest(form1, URL1, basicDomain1);
if (!response_.IsSuccess)
{
await Application.Current.MainPage.DisplayAlert("Error", response_.Message, "Network Problem!!");
return;
}
}
}
}
But it shows the error "Can not access the closed stream." How to fix this error?

FCM PushNotification to iOS device from .NET

Is it possible to use Firebase's FCM to send apns push notifications to an ios device?
Desired Workflow:
iOS app sends request to my .NET server to provide it the push token. My .NET server will handle all push notifications. So I assume this would be http requests to firebase and firebase would send out the notification?
Is this workflow possible?
I have worked with Android Applications using Firebase's FCM.. so i think there must be way to work with ios.
here is the snippet of code for sending push notification using fcm in c#.
NotifBooking objnotif = new NotifBooking();
string ApplicationID = "AIzaSyCBM20ZXXXXXXXXXXjog3Abv88";
string SENDER_ID = "962XXXXXXX";
var value = "Alert :" + Message + ""; //message text box
WebRequest tRequest;
tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post";
tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", ApplicationID)); tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
tRequest.ContentType = "application/json";
var data1 = new
{
to = "" + dt.Rows[i]["RegId"].ToString().Trim() + "",//Device RegID
priority = "high",
notification = new
{
body = Message,
title = Heading,
is_background = true,
image = "abc.com/images/1_icon.png",
appicon = "abc.com/images/1_icon.png",
sound = "default"
},
data = new
{
//body = Message,
//is_background=false,
//title = "Test FCM",
//appicon = "myicon",
image = "abc.com/images/1_icon.png"
},
};
Console.WriteLine(data1);
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data1);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
string str = sResponseFromServer;
}
}
}
}
objnotif.data = json;
}
You should get device token from Firebase and register the current user in backend side with the same token.
After that, you can send push notifications from your backend.
Put this code in AppDelegate class.
Call InitAPNS() from FinishedLaunching.
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
//TODO: save token and register one in backend side
Settings.DeviceTokenFCM = InstanceId.SharedInstance.Token;
}
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
ShowPushMessage(userInfo);
}
private void ShowPushMessage(NSDictionary userInfo)
{
if (userInfo != null)
{
try
{
var apsDictionary = userInfo["aps"] as NSDictionary;
var alertDictionary = apsDictionary?["alert"] as NSDictionary;
var body = alertDictionary?["body"].ToString();
var title = alertDictionary?["title"].ToString();
var window = UIApplication.SharedApplication.KeyWindow;
var vc = window.RootViewController;
var alert = UIAlertController.Create(title, body, UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Cancel, null));
vc.PresentViewController(alert, animated: true, completionHandler: null);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
private void InitAPNS()
{
// Monitor token generation
InstanceId.Notifications.ObserveTokenRefresh(TokenRefreshNotification);
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.Sound, (granted, error) =>
{
if (granted)
{
InvokeOnMainThread(UIApplication.SharedApplication.RegisterForRemoteNotifications);
}
});
}
else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
new NSSet());
UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
UIApplication.SharedApplication.RegisterForRemoteNotifications();
}
else
{
UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
}
Firebase.Core.App.Configure();
}
private void TokenRefreshNotification(object sender, NSNotificationEventArgs e)
{
ConnectToFCM();
}
private void ConnectToFCM()
{
var tokenFirebase = InstanceId.SharedInstance.Token;
////registation token in background thread
System.Threading.Tasks.Task.Run(() =>
{
if (!string.IsNullOrEmpty(tokenFirebase))
{
Firebase.CloudMessaging.Messaging.SharedInstance.SetApnsToken(tokenFirebase, ApnsTokenType.Production);
}
});
Messaging.SharedInstance.ShouldEstablishDirectChannel = true;
}
IOS push Notification using C#.I have worked with Android Applications using Firebase's FCM.here is the snippet of code for sending push notification using fcm in c#.
**
namespace push
{
public partial class pushios : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SendPushNotification(txtDeviceToken.Text, txtMessage.Text);
}
private void SendPushNotification(string deviceToken,string message)
{
try
{
//Get Certificate
var appleCert = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Files/Certificate/IOS/Production_Certificate.p12"));
// Configuration (NOTE: .pfx can also be used here)
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, appleCert, "1234567890");
// Create a new broker
var apnsBroker = new ApnsServiceBroker(config);
// Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
{
aggregateEx.Handle(ex =>
{
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
string desc = $"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}";
Console.WriteLine(desc);
Label1.Text = desc;
}
else
{
string desc = $"Apple Notification Failed for some unknown reason : {ex.InnerException}";
// Inner exception might hold more useful information like an ApnsConnectionException
Console.WriteLine(desc);
Label1.Text = desc;
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) =>
{
Label1.Text = "Apple Notification Sent successfully!";
};
var fbs = new FeedbackService(config);
fbs.FeedbackReceived += (string devicToken, DateTime timestamp) =>
{
};
apnsBroker.Start();
if (deviceToken != "")
{
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken,
Payload = JObject.Parse(("{\"aps\":{\"badge\":1,\"sound\":\"oven.caf\",\"alert\":\"" + (message + "\"}}")))
});
}
apnsBroker.Stop();
}
catch (Exception)
{
throw;
}
}
}
**
I have worked with Android Applications using Firebase's FCM..
namespace pushios.Controllers
{
public class HomeController : ApiController
{
[HttpGet]
[Route("sendmessage")]
public IHttpActionResult SendMessage()
{
var data = new {
to = "xxxxxxxxxxxxxxxxxxx",
data = new
{
body="Test",
confId= "6565",
pageTitle= "test",
pageFormat= "",
dataValue= "",
title= "C#",
webviewURL= "",
priority = "high",
notificationBlastID = "0",
status = true
}
};
SendNotification(data);
return Ok();
}
public void SendNotification(object data)
{
var Serializer = new JavaScriptSerializer();
var json = Serializer.Serialize(data);
Byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(json);
SendNotification(byteArray);
}
public void SendNotification(Byte[] byteArray)
{
try
{
String server_api_key = ConfigurationManager.AppSettings["SERVER_API_KEY"];
String senderid = ConfigurationManager.AppSettings["SENDER_ID"];
WebRequest type = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
type.Method = "post";
type.ContentType = "application/json";
type.Headers.Add($"Authorization: key={server_api_key}");
type.Headers.Add($"Sender: id={senderid}");
type.ContentLength = byteArray.Length;
Stream datastream = type.GetRequestStream();
datastream.Write(byteArray, 0, byteArray.Length);
datastream.Close();
WebResponse respones = type.GetResponse();
datastream = respones.GetResponseStream();
StreamReader reader = new StreamReader(datastream);
String sresponessrever = reader.ReadToEnd();
reader.Close();
datastream.Close();
respones.Close();
}
catch (Exception)
{
throw;
}
}
}
}
```

Spring MVC returns 405 for api call made from my android client

I have an android app which is making api requests to my server running Spring MVC. The RestController works fine when I make a request from the browser but it responds with 404 when I am making requests from android. Not sure why
Here is code snippet from Android app making requests
public class AsyncFetch extends AsyncTask<Pair<String, String>, String, String> {
public ProgressDialog pdLoading;
private HttpURLConnection conn;
private String urlStr;
private String requestMethod = "GET";
public AsyncFetch(String endpoint, Context ctx)
{
pdLoading = new ProgressDialog(ctx);
Properties reader = PropertiesReader.getInstance().getProperties(ctx, "app.properties");
String host = reader.getProperty("host", "10.0.2.2");
String port = reader.getProperty("port", "8080");
String protocol = reader.getProperty("protocol", "http");
String context = reader.getProperty("context", "");
this.urlStr = protocol+"://"+host+":"+port+context+endpoint;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(Pair<String, String>... params) {
URL url;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod(requestMethod);
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made`enter code here`
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
Spring MVC Controller
#RestController
public class ApiController {
#RequestMapping(value = "homefeed", method=RequestMethod.GET)
public String homefeed(#RequestParam(value="userId", required = false) Integer id, #RequestParam(value="search", required = false) String search, #RequestParam(value="page", required = false, defaultValue = "0") Integer page) { ... }
}
localhost:8080/api/homefeed -- works
127.0.0.1:8080/api/homefeed -- works
My Public IP:8080/api/homefeed -- does not works
10.0.2.2:8080/api/homefeed -- android emulator to localhost -- does not work
10.0.2.2:8080/Some resource other than the api endpoint -- works
Any help is highly appreciable, have wasted quiet some time in debugging.

Windows 8 universal app ASP.Net web Api

I'm trying binding image from ASP.NET Web Api service there i have contorller
public class ImageController : ApiController
{
public HttpResponseMessage GetImage()
{
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StreamContent(new FileStream("FileAddress", FileMode.Open));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return response;
}
}
client side is Windows 8 universal app there are next code
private async void Button_Click(object sender, RoutedEventArgs e)
{
Uri datauri = new Uri("http://localhost:63606/Api/Image");
var client = new HttpClient();
var datafil = await client.GetAsync(datauri);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, datauri);
HttpResponseMessage response = await client.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead);
InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
}
I don't know what to do , I couldn't get image for example in BitmapImage file.
inYou can do the following
public class ImageController : ApiController
{
public HttpResponseMessage GetImage()
{
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StreamContent(new FileStream("FileAddress", FileMode.Open));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return response;
}
}
and in the WinRt app write following code
private async void Button_Click(object sender, RoutedEventArgs e)
{
Uri datauri = new Uri("Api Uri");
BitmapImage image= new BitmapImage(datauri);
// if you want show result in XAML Controls
Image1.Sourse=image;
}
in XAML
<Image x:Name="Image1" HorizontalAlignment="Left" Height="292" Margin="48,413,0,0" VerticalAlignment="Top" Width="310"/>
Second way if you want get many photo is that you can create new folder in API folder and named it for example PhotoRepository add photo in this folder and get photo via it URI
private void Button_Click(object sender, RoutedEventArgs e)
{
Uri datauri = new Uri("http://localhost:63606/PhotoReposytory/"photo name".jpg");
//jpg or other format
BitmapImage foto = new BitmapImage(datauri);
Image1.Source = foto;
}

how to use FileSystemWatcher using asp.net(C#)

SENARIO: i have few folders on my FTP server, belongs to particular user. Suppose i have 10GB total space and i assign 1GB to each user i.e can accomodate 10 users having 1GB each.
now users can add/delete/edit any type of file to utilize the storage space. All i need to do is to restrict users not to exceed 1gb space for their file storage. For this i want to use FileSystemWatcher to notify me that a user had created/deleted/edited a file so that i can minimize the space from 1gb incase of creation of a file or add a space incase of deletion.
this is the piece of coding using FSW. when user gets loged-in with proper id and password, respective folder is opened (present at FTP server) where he can add/delete/edit any type of file and according to that i hav to monitor d space ulitilized by him.
but d problem is the event handlers (written in console). i dont understand what happens when this code is being runned... i dontknow how to use FSW class so that i can monitor d changes user is making in his folder.
please help ... THANX
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
public class _Default: System.Web.UI.Page {
public class ClsFileSystemWatcher {
public static void OnChanged(object source, FileSystemEventArgs e) {
Console.WriteLine("File "+e.FullPath+" :"+e.ChangeType);
}
public static void OnDeleted(object source, FileSystemEventArgs e) {
Console.WriteLine("File "+e.FullPath+" :"+e.ChangeType);
}
public static void OnCreated(object source, FileSystemEventArgs e) {
Console.WriteLine("File "+e.FullPath+" :"+e.ChangeType);
}
public static void OnRenamed(object source, RenamedEventArgs e) {
Console.WriteLine("File "+e.OldFullPath+" [Changed to] "+e.FullPath);
}
public static void OnError(object source, ErrorEventArgs e) {
Console.WriteLine("Error "+e);
}
public void FileWatcher(string InputDir) {
using (FileSystemWatcher fsw = new FileSystemWatcher()) {
fsw.Path = InputDir;
fsw.Filter = #"*";
fsw.IncludeSubdirectories = true;
fsw.NotifyFilter = NotifyFilters.FileName|NotifyFilters.Attributes|NotifyFilters.LastAccess|NotifyFilters.LastWrite|NotifyFilters.Security|NotifyFilters.Size|NotifyFilters.CreationTime|NotifyFilters.DirectoryName;
fsw.Changed += OnChanged;
fsw.Created += OnCreated;
fsw.Deleted += OnDeleted;
fsw.Renamed += OnRenamed;
fsw.Error += OnError;
fsw.EnableRaisingEvents = true;
//string strOldFile = InputDir + "OldFile.txt";
//string strNewFile = InputDir + "CreatedFile.txt";
//// Making changes in existing file
//using (FileStream stream = File.Open(strOldFile, FileMode.Append))
//{
// StreamWriter sw = new StreamWriter(stream);
// sw.Write("Appending new line in Old File");
// sw.Flush();
// sw.Close();
//}
//// Writing new file on FileSystem
//using (FileStream stream = File.Create(strNewFile))
//{
// StreamWriter sw = new StreamWriter(stream);
// sw.Write("Writing First line into the File");
// sw.Flush();
// sw.Close();
//}
//File.Delete(strOldFile);
//File.Delete(strNewFile);
// Minimum time given to event handler to track new events raised by the filesystem.
Thread.Sleep(1000);
}
}
}
private DAL conn;
private string connection;
private string id = string.Empty;
protected void Page_Load(object sender, EventArgs e) {
connection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\project\\Desktop\\BE prj\\dbsan.mdb;Persist Security Info=False";
conn = new DAL(connection);
////*** Opening Respective Folder of a User ***////
DirectoryInfo directories = new DirectoryInfo(#"C:\\Inetpub\\ftproot\\san\\");
DirectoryInfo[] folderList = directories.GetDirectories();
if (Request.QueryString["id"] != null) {
id = Request.QueryString["id"];
}
string path = Path.Combine(#"C:\\Inetpub\\ftproot\\san\\", id);
int folder_count = folderList.Length;
for (int j = 0; j < folder_count; j++) {
if (Convert.ToString(folderList[j]) == id) {
Process p = new Process();
p.StartInfo.FileName = path;
p.Start();
}
}
ClsFileSystemWatcher FSysWatcher = new ClsFileSystemWatcher();
FSysWatcher.FileWatcher(path);
}
}
Each time you reload the page you create new FSW - in that case you won't get any events raised, because from the point of newly created FSW nothing was changes. Try to preserve your FileSystemWatcher object in the Session state.
So flow would look like:
User logs in – you create FSW and preserve it in Session
User reloads the page – get FSW from Session (do not create new one)
You should create a worker role (service) for this type of thing. I think it is not appropriate to have something like this inside of a page.

Resources