How to capture image from camera and convert the image to base 64 string send to the server in xamarin forms? - 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?

Related

app crashes when trying to send multiple fcm messages programmatically

i am trying to create a messaging app using xamarin.forms. i created a send button and added the following code:
private async void send_Clicked(object sender, EventArgs e)
{
await Task.Run(() => SendNotification(token, "title", message.Text));
}
and the sendnotification is as follows:
public string SendNotification(string DeviceToken, string title, string msg)
{
var result = "-1";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
httpWebRequest.Method = "POST";
var payload = new
{
//to= "/topics/klm",
to = DeviceToken,
//to = "egjLx6VdFS0:APA91bGQMSSRq_wCzywNC01zJi4FBtHXrXuL-p4vlkl3a3esdH8lxo7mQZUBlrTi7h-6JXx0GrJbwc9Vx6M5Q4OV_3CArcdlP0XMBybervQvfraWvqCgaa75gu9SVzjY4V_qd36JGg4A",
priority = "high",
content_available = true,
data = new
{
text = msg,
},
};
var serializer = new JsonSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(payload);
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
this is private string webAddr = "https://fcm.googleapis.com/fcm/send";
when i click send the first time, i receive the message perfectly, when i hit send the second time, the app freezes then crashes and asks me if i want to close the app or wait. why is this happening? thanks in advance

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;
}
}
}
}
```

How to get image from HTTP URL in Windows Phone?

How do I get image from http url, my url is like:
"http://accd.com/abc.htm",
how do I get image from it?
So
public static BitmapImage Base64StringToBitmap(string source)
{
var ims = new InMemoryRandomAccessStream();
var bytes = Convert.FromBase64String(source);
var dataWriter = new DataWriter(ims);
dataWriter.WriteBytes(bytes);
dataWriter.StoreAsync();
ims.Seek(0);
var img = new BitmapImage();
img.SetSource(ims);
return img;
}
You can use the web client like this :
var webClient = new WebClient();
webClient.DownloadStringAsync(new Uri("http://accd.com/abc.htm"));
webClient.DownloadStringCompleted += (sender, eventArgs) => (eventArgs.Result); //Here is your base 64 image code, you can use the Base64StringToBitmap function
May be with using a webclient
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri("your http url"), wc);
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(e.Result);
imgLogoData.Source = bitmapImage;
imgLogoData.Height = 200;
}
catch (Exception ex)
{
MessageBox.Show(AppResources.resErrorOccured);
ExceptionHelper.WriteLog(ex);
}
}
And to convert a Base64 string to BitmapImage just follow this method
public static BitmapImage base64image(string base64string)
{
byte[] fileBytes = Convert.FromBase64String(base64string);
using (MemoryStream ms = new MemoryStream(fileBytes, 0, fileBytes.Length))
{
ms.Write(fileBytes, 0, fileBytes.Length);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(ms);
return bitmapImage;
}
}
So that, for an Image declared in xaml like this
Add an image to your XAML, such as this:
<Image x:Name="imgLogoData" Height="50" Width="50" />
You can then set the source, like this:
imgLogoData.Source = base64image(yourBase64string);

Pdf's fields should remain editable using itextsharp in asp.net

I have a fillable pdf. In which i have few textboxes.
I fill these fields by using following code(itextsharp).
DataTable dt = new DataTable();
String pdfPath1 = Server.MapPath("pdfs\\transmittal2.pdf");
if (File.Exists(pdfPath1))
{
dt = objClsTransmittal.GetTransmittal(jobid, cid);
String comment = "Correspondence generated for " + dt.Rows[0]["Recipient"].ToString();
var formfield = PDFHelper.GetFormFieldNames(pdfPath1);
formfield["DocDate"] = DateTime.Now.ToLongDateString();
formfield["Address1"] = dt.Rows[0]["Company"].ToString();
formfield["Address2"] = dt.Rows[0]["Address1"].ToString();
formfield["PropertyAddress"] = dt.Rows[0]["PropertyAddress"].ToString();
formfield["Job"] = dt.Rows[0]["JobID"].ToString();
formfield["Name"] = dt.Rows[0]["Recipient"].ToString();
formfield["CityStateZip"] = dt.Rows[0]["address2"].ToString();
formfield["E-mail"] = dt.Rows[0]["Email"].ToString();
var pdfcontent = PDFHelper.GeneratePDF(pdfPath1, formfield);
PDFHelper.ReturnPDF(pdfcontent, "Transmittal.pdf");
}
Currently its downloded as read only pdf.
when this pdf gets downloaded, i want that all fields still remain fillable, with the text i have filled in pdf. So that i can edit the text.
I'm looking forward for your replies.
Thanks.
EDIT
PdfHelper is my custom class. In which i have used following code:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.IO;
using iTextSharp.text.pdf;
public class PDFHelper
{
public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
{
var fields = new Dictionary<string, string>();
var reader = new PdfReader(pdfPath);
foreach (DictionaryEntry entry in reader.AcroFields.Fields)
fields.Add(entry.Key.ToString(), string.Empty);
reader.Close();
return fields;
}
public static byte[] GeneratePDF(string pdfPath, Dictionary<string, string> formFieldMap)
{
var output = new MemoryStream();
var reader = new PdfReader(pdfPath);
var stamper = new PdfStamper(reader, output);
var formFields = stamper.AcroFields;
foreach (var fieldName in formFieldMap.Keys)
formFields.SetField(fieldName, formFieldMap[fieldName]);
stamper.FormFlattening = true;
stamper.Close();
reader.Close();
return output.ToArray();
}
public static string GetExportValue(AcroFields.Item item)
{
var valueDict = item.GetValue(0);
var appearanceDict = valueDict.GetAsDict(PdfName.AP);
if (appearanceDict != null)
{
var normalAppearances = appearanceDict.GetAsDict(PdfName.N);
if (normalAppearances != null)
{
foreach (var curKey in normalAppearances.Keys)
if (!PdfName.OFF.Equals(curKey))
return curKey.ToString().Substring(1); // string will have a leading '/' character, so remove it!
}
}
var curVal = valueDict.GetAsName(PdfName.AS);
if (curVal != null)
return curVal.ToString().Substring(1);
else
return string.Empty;
}
public static void ReturnPDF(byte[] contents)
{
ReturnPDF(contents, null);
}
public static void ReturnPDF(byte[] contents, string attachmentFilename)
{
var response = HttpContext.Current.Response;
if (!string.IsNullOrEmpty(attachmentFilename))
response.AddHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);
response.ContentType = "application/pdf";
response.BinaryWrite(contents);
response.End();
}
Your code line
stamper.FormFlattening = true;
instructs iTextSharp to flatten the form fields, i.e. to integrate them into the page content and remove the form field annotations.
As you want to keep the form fields as editable fields, don't flatten the form.
Error: Cannot convert type in PDFHelper.cs
public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
{
var fields = new Dictionary<string, string>();
var reader = new PdfReader(pdfPath);
foreach (DictionaryEntry entry in reader.AcroFields.Fields) //ERROR: 'System.Collections.Generic.KeyValuePair' to 'System.Collections.DictionaryEntry'
{
fields.Add(entry.Key.ToString(), string.Empty);
}
reader.Close();
return fields;
}
'System.Collections.Generic.KeyValuePair' to 'System.Collections.DictionaryEntry'

Trying to authorize facebook Canvas app in ASP.net Web Forms

I've had some Page Tab apps working, just basic authorization as I don't need anything except name / id for what I'm doing - but I've tried the same method with the canvas app and it's not working. It seems to be with the redirect back, and I really can't see where I'm going wrong based on facebook's documentation for canvas apps http://developers.facebook.com/docs/appsonfacebook/tutorial/#auth
On loading I show a button, on clicking that it tries to get authorisation but it's not working. I've checked and double checked that I'm using the canvas url as the redirect but all I'm getting is a 404 (which is wrong as the page definitely exists, or else the button wouldn't appear). The URL on the 404 page is what really bemuses me, it's:
http://apps.mydomain.co.uk/myappname/https%3a%2f%2fwww.facebook.com%2fdialog%2foauth%3fclient_id%3d999999999999%26redirect_uri%3dhttp%253a%252f%252fapps.mydomain.co.uk%252fmyappname%252f
It has to be something to do with the redirection - any help would be appreciated.
Here's my code (shortened for clarity, urls changed):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string error = Request.QueryString["error_reason"];
if (String.IsNullOrEmpty(error))
{
if (Request.Form["signed_request"] != null)
{
signedRequest();
}
if (String.IsNullOrEmpty(_auth))
{
intro.Visible = true;
main.Visible = false;
}
else
{
intro.Visible = false;
main.Visible = true;
}
}
else
{
// show intro page
intro.Visible = true;
main.Visible = false;
}
}
}
protected void Authorise_Click(object sender, EventArgs e)
{
// redirect if needs auth
if (String.IsNullOrEmpty(_auth))
{
// get authorisation
string id = "999999999999";
string canvas = Server.UrlEncode("http://apps.mydomain.co.uk/myappname/");
string redir = Server.UrlEncode("https://www.facebook.com/dialog/oauth?client_id="+ id +"&redirect_uri=" + canvas); // test
Response.Write("<script>top.location.href='" + redir + "'</script>");
}
else
{
// already authorised
// go straight to main page
}
}
private void signedRequest()
{
string sreq = Request.Form["signed_request"];
string[] splitPayload = sreq.Split('.');
string sig = splitPayload[0];
string payload = splitPayload[1];
Dictionary<string, string> JSONpayload = DecodePayload(payload);
_auth = JSONpayload["user_id"].ToString();
_code = JSONpayload["oauth_token"].ToString();
if (!String.IsNullOrEmpty(JSONpayload["oauth_token"]))
{
var fb = new FacebookClient(JSONpayload["oauth_token"]);
var result = (IDictionary<string, object>)fb.Get("/me");
_name = (string)result["name"];
//Response.Write("<br /><br />RESULT: " + result);
ViewState["name"] = _name;
Session["name"] = _name;
}
ViewState["id"] = _auth;
Session["id"] = _auth;
}
private Dictionary<string, string> DecodePayload(string payload)
{
var encoding = new UTF8Encoding();
var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
var json = encoding.GetString(base64JsonArray);
var jObject = JObject.Parse(json);
Response.Write("jObject: " + jObject);
var parameters = new Dictionary<string, string>();
parameters.Add("user_id", (string)jObject["user_id"] ?? "");
parameters.Add("oauth_token", (string)jObject["oauth_token"] ?? "");
var expires = ((long?)jObject["expires"] ?? 0);
parameters.Add("expires", expires > 0 ? expires.ToString() : "");
parameters.Add("profile_id", (string)jObject["profile_id"] ?? "");
if (jObject["page"] != null)
{
var jObjectPage = JObject.Parse(jObject["page"].ToString());
bool isPageLiked = bool.Parse(jObjectPage["liked"].ToString());
parameters.Add("is_Liked", isPageLiked.ToString() ?? "");
}
else
{
_liked = false;
}
return parameters;
}

Resources