How to display retrieved Signature image byte array on SignaturePad - xamarin

I have Page X with a SignaturePad on my Xamarin.Forms app and I save the signature into the database in the following way:
if (!sp.IsBlank)
{
Stream image = await sp.GetImageStreamAsync(SignatureImageFormat.Png);
using (BinaryReader br = new BinaryReader(image))
{
br.BaseStream.Position = 0;
byte[] SignatureImage = br.ReadBytes((int)image.Length);
}
}
I save this byte array in my SQL database table. I navigate to a couple of other pages in my app and then go back to Page X and want to reload all the information into this page from the saved information in the database. How do I reload the Signature? Do I need to save the signature as strokes or points instead? How do I save strokes or points in the database? Some sample code would be really helpful
Thank you.

Related

Setting link URL with Google Docs API doesn't result in update of image

I'm trying to update a placeholder image with a new image that has an updated URL. The URL in fact is a valid Google Static Map URL that I'm using in other contexts successfully. I'm using the Google Document API to manipulate the document. Following the code I've been using:
var element = body.findElement(DocumentApp.ElementType.INLINE_IMAGE).getElement();
var imageMap = element.asInlineImage();
// if there was an image found in document
if (imageMap != null) {
// get current parent and index inside parent
var parent = imageMap.getParent();
var childIndex = parent.getChildIndex(imageMap);
// remove image from paragraph
imageMap = imageMap.removeFromParent();
// get static image url for territory
var url = getStaticMapURLForTerritory(id);
Logger.log(url);
imageMap.setLinkUrl(url);
// create a new image
parent.insertInlineImage(childIndex, imageMap)
}
This seems to work fine in that it does update the image url correctly. However, the image itself (the result of the url) is not updated. When I click on the link URL it does return the correct image.
Is there a way to force a refetch of the image blob associated with the URL? I've also attempted to use UrlFetchApp but that complains about a missing size parameter (google static api) which is certainly included in the url string and within the max 640x640 bounds.
I've exhausted all my options unless....
TIA, --Paul
setLinkUrl only does that: sets the link. To actually add a new image you'll have to get its blob:
function replaceImage() {
// [...]
// get static image url for territory
const url = getStaticMapURLForTerritory(id)
const response = UrlFetchApp.fetch(url)
// create a new image
parent.insertInlineImage(childIndex, response.getBlob())
.setAltDescription(img.getAltDescription())
.setAltTitle(img.getAltTitle())
.setWidth(img.getWidth())
.setHeight(img.getHeight())
.setLinkUrl(url)
}
References
Class InlineImage (Google Apps Script reference)

Is there any way of suppressing ‘Do you want to save changes to xxx.pdf before closing’ dialog using ABCpdf

We are reading the adobe form template using ABCpdf , populating form fields with values retrieved from database and amending them into a single PDF document and sending the document back as File stream in the HTTP response to the users in a ASP.net MVC App.
This approach is working fine and PDF documents are getting generated successfully. But when the user choose to open the generated PDF file and try to close it, they are being prompted ‘Do you want to save changes to xxx.pdf before closing’ dialog from Adobe Acrobat. Is there any way of suppressing this message using ABC pdf?.
Following is the code we are using to generate the PDF.
public byte[] GeneratePDF(Employee employee, String TemplatePath)
{
string[] FieldNames;
Doc theDoc;
MemoryStream MSgeneratedPDFFile = new MemoryStream();
//Get the PDF Template and read all the form fields inside the template
theDoc = new Doc();
theDoc.Read(HttpContext.Current.Server.MapPath(TemplatePath));
FieldNames = theDoc.Form.GetFieldNames();
//Navigate through each Form field and populate employee details
foreach (string FieldName in FieldNames)
{
Field theField = theDoc.Form[FieldName];
switch (FieldName)
{
case "Your_First_Name":
theField.Value = employee.FirstName;
break;
default:
theField.Value = theField.Name;
break;
}
//Remove Form Fields and replace them with text
theField.Focus();
theDoc.Color.String = "240 240 255";
theDoc.FillRect();
theDoc.Rect.Height = 12;
theDoc.Color.String = "220 0 0";
theDoc.AddText(theField.Value);
theDoc.Delete(theField.ID);
}
return theDoc.GetData();
}
Today I ran into this problem too, but with a PDF with no form fields. I ran #CharlieNoTomatoes code and confirmed the FieldNames collection was definitely empty.
I stepped through the various stages of my code and found that if I saved the PDF to the file system and opened from there it was fine. Which narrowed it down to the code that took the abcpdf data stream and sent it directly to the user (I normally don't bother actually saving to disk). Found this in the WebSuperGoo docs and it suggested my server might be sending some extra rubbish in the Response causing the file to be corrupted.
Adding Response.End(); did the trick for me. The resulting PDF files no longer displayed the message.
byte[] theData = _thisPdf.Doc.GetData();
var curr = HttpContext.Current;
curr.Response.Clear();
curr.Response.ContentType = "application/pdf";
curr.Response.AddHeader("Content-Disposition", "attachment; filename=blah.pdf");
curr.Response.Charset = "UTF-8";
curr.Response.AddHeader("content-length", theData.Length.ToString());
curr.Response.BinaryWrite(theData);
curr.Response.End();
I ran into this problem, as well. I found a hint about "appearance streams" here:
The PDF contains form fields and the NeedAppearances entry in the interactive form dictionary is set to true. This means that the conforming PDF reader will generate an appearance stream where necessary for form fields in the PDF and as a result the Save button is enabled. If the NeedAppearances entry is set to false then the conforming PDF reader should not generate any new appearance streams. More information about appearance streams in PDF files and how to control them with Debenu Quick PDF Library.
So, I looked for "appearance" things in the websupergoo doc and was able to set some form properties and call a field method to get rid of the "Save changes" message. In the code sample above, it would look like this:
Edit: After exchanging emails with fast-and-helpful WebSuperGoo support about the same message after creating a PDF with AddImageHtml that WASN'T fixed by just setting the form NeedAppearances flag, I added the lines about Catalog and Atom to remove the core document NeedAppearances flag that gets set during AddImageHtml.
public byte[] GeneratePDF(Employee employee, String TemplatePath)
{
string[] FieldNames;
Doc theDoc;
MemoryStream MSgeneratedPDFFile = new MemoryStream();
//Get the PDF Template and read all the form fields inside the template
theDoc = new Doc();
theDoc.Read(HttpContext.Current.Server.MapPath(TemplatePath));
FieldNames = theDoc.Form.GetFieldNames();
//Tell PDF viewer to not create its own appearances
theDoc.Form.NeedAppearances = false;
//Generate appearances when needed
theDoc.Form.GenerateAppearances = true;
//Navigate through each Form field and populate employee details
foreach (string FieldName in FieldNames)
{
Field theField = theDoc.Form[FieldName];
switch (FieldName)
{
case "Your_First_Name":
theField.Value = employee.FirstName;
break;
default:
theField.Value = theField.Name;
break;
}
//Update the appearance for the field
theField.UpdateAppearance();
//Remove Form Fields and replace them with text
theField.Focus();
theDoc.Color.String = "240 240 255";
theDoc.FillRect();
theDoc.Rect.Height = 12;
theDoc.Color.String = "220 0 0";
theDoc.AddText(theField.Value);
theDoc.Delete(theField.ID);
}
Catalog cat = theDoc.ObjectSoup.Catalog;
Atom.RemoveItem(cat.Resolve(Atom.GetItem(cat.Atom, "AcroForm")), "NeedAppearances");
return theDoc.GetData();
}

Custom live tile rendering issue on Windows Phone (7/8)

In my Windows Phone app's main page, users can click a button to do some stuff and that will trigger the live tile to update.
The problem I am having is, if the user clicks the button and then hit the phone's Back button really quickly, the live tile sometimes will not render properly. This issue rarely happens, but it does happen and when it happens it just looks bad...
The way I implement the live tile is, create a user control that looks exactly the same as the live tile and then save it to isolated storage. Then retrieve it and store it in a FliptileData object. Finally I call the Update method on the ShellTile. Please see the following piece of code to demonstrate the process.
// the function that saves the user control to isolated storage
public Uri SaveJpegToIsolatedStorage(FrameworkElement tile, string suffix, int tileWidth = 336, int tileHeight = 336)
{
var bmp = new WriteableBitmap(tileWidth, tileHeight);
// Force the content to layout itself properly
tile.Measure(new Size(tileWidth, tileHeight));
tile.Arrange(new Rect(0, 0, tileWidth, tileHeight));
bmp.Render(tile, null);
bmp.Invalidate();
// Obtain the virtual store for the application
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(IsolatedStorageFileName + suffix, FileMode.Create, myStore))
{
try
{
bmp.SaveJpeg(fileStream, tileWidth, tileHeight, 0, 100);
}
catch (Exception)
{
return null;
}
}
return new Uri("isostore:/" + IsolatedStorageFileName + suffix, UriKind.Absolute);
}
// save the user control to isolated storage and prepare the FlipTileData object
wideFrontTileImage = SaveJpegToIsolatedStorage((UserControl)this.WideFrontTile, "_wide_front", 691);
var flipTileData = new FlipTileData();
flipTileData.WideBackgroundImage = wideFrontTileImage;
return flipTileData;
// update the live tile
var shellTile = ShellTile.ActiveTiles.FirstOrDefault();
shellTile.Update(customTile.GetFlipTileData(data.UndoneMemosCount == "0" && data.TotalMemosCount == "0"));
I think the reason that's causing all this is, when the user clicks the Back button too quickly, the OS terminates all the processes running within the app and the rendering wasn't done at that time. I'm thinking if there's a way to know when the rendering is finished, so I can cancel the Back button and wait until it's finished then manually exit the app. But I simply dunno how...
Any help on this one will be greatly appreciated!
I have ran into similar issue in my WP8 app. The problem was that I was updating my Tile in ApplicationDeactivated event handler. The thing is you should not update your tiles there, but rather in your MainPage.OnNavigatedFrom override. Once I changed this, it works just fine.

How to store image in SqlCe Database for windows Phone

not sure how to do this since there is no ado.net in Windows Phone. Would appreciate if you can show me some code and sample.
Thanks
Use image data type, see this sample: http://erikej.blogspot.com/2009/11/how-to-save-and-retrieve-images-using.html
I would suggest to approaches:
1- If your images are not going to be very large, then you can store Base64 string of image data as a string field in database.
var base64String = Convert.ToBase64String(imageData); // and store this to database
var imageData = Convert.FromBase64String(imageDataString); // read image data from database
2- otherwise you can assign your image (or database record) a unique GUID and store your image in IsolatedStorageFile.
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var writer = new BinaryWriter(new IsolatedStorageFileStream(filename, System.IO.FileMode.Create, isf)))
{
writer.Write(imageData);
}
}
will add code in a minute

Create image serving URL for new Blob file

After using the ImagesService to transform an uploaded image, I would like to store it back into a new Blob file and make it available through getServingUrl() as provided by the ImagesService.
Storing the image in a new AppEngineFile as described here works fine and I am able to open and view it locally using the dev server.
However when passing the blobKey for the new AppEngineFile to ImagesService.getServingUrl() a
java.lang.IllegalArgumentException: Could not read blob.
exception is thrown. Any ideas what the problem could be? This is the code I use to transform and store an uploaded image (blobKey and blobInfo correspond to the uploaded file, not the newly created one).
/* Transform image in existing Blob file */
Image originalImage = ImagesServiceFactory.makeImageFromBlob(blobKey);
Transform verticalFlip = ImagesServiceFactory.makeVerticalFlip();
ImagesService imagesService = ImagesServiceFactory.getImagesService();
Image newImage = imagesService.applyTransform(verticalFlip, originalImage);
/* Store newImage in an AppEngineFile */
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = fileService.createNewBlobFile(blobInfo.getContentType());
FileWriteChannel writeChannel = fileService.openWriteChannel(file, true);
ByteBuffer buffer = ByteBuffer.wrap(newImage.getImageData());
writeChannel.write(buffer);
/* closeFinally assigns BlobKey to new file object */
writeChannel.closeFinally();
BlobKey newBlobKey = fileService.getBlobKey(file);
Edit:
The above code is correct, the problem was storing a String representation of the new blob key using newBlobKey.toString() instead of newBlobKey.getKeyString().
Why would you want to do that? Once you transform an image it is cached and anyway it is always fast. If you really feel you want to save it just use urlfetch to read the data and store them in the BlobStore ;-)
The following works fine when executed at the end of the code posted in the question:
String url = imagesService.getServingUrl(newBlobKey)
The URL can then be used to scale and crop the new image as described in the docs
http://code.google.com/appengine/docs/java/images/overview.html#Transforming_Images_from_the_Blobstore

Resources