multi lining files in IsolatedStorage # Windows Phone 7 - windows-phone-7

i have created some files in the IO
in the "car" files, i would like to put some other reference like model, color etc...
so my question is : is it possible to have a multi-lining files in the IO
if yes how can i get them in the streamreader
// i want to storage many parameters in a file and find them again with the streamreader
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
//reception des parametres de la listbox
base.OnNavigatedTo(e);
string parameter = this.NavigationContext.QueryString["parameter"];
this.tbTitre.Text = parameter;
try
{
//Create a new StreamReader
StreamReader editionDevisReader = null;
IsolatedStorageFile probyOrange = IsolatedStorageFile.GetUserStoreForApplication();
//Read the file from the specified location.
editionDevisReader = new StreamReader(new IsolatedStorageFileStream("devis\\"+parameter+".txt", FileMode.Open, probyOrange));
//Read the contents of the file .
string textFile = editionDevisReader.ReadLine();
//Write the contents of the file to the TextBlock on the page.
tbTitre.Text = textFile;
while (editionDevisReader != null)
{
RowDefinition rowdefinition = new RowDefinition();
TextBlock textblock = new TextBlock();
textblock.HorizontalAlignment = new System.Drawing.Size(48, 20);
}
editionDevisReader.Close();
}
catch
{
//If the file hasn't been created yet.
tbTitre.Text = "veuillez d abord creer le fichier";
}
thx a lot all

Yes, you can save anything (up to a point) in a file:
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var isfs = new IsolatedStorageFileStream("myfile.txt", FileMode.OpenOrCreate, store))
{
using (var sw = new StreamWriter(isfs))
{
sw.Write("anything really. Here it's just a string but could be a serialized object, etc.");
sw.Close();
}
}
}
You can then read the file with:
var result = string.Empty;
try
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!store.FileExists("myfile.txt"))
{
return result;
}
using (var isfs = new IsolatedStorageFileStream("myfile.txt", FileMode.Open, store))
{
using (var sr = new StreamReader(isfs))
{
string lineOfData;
while ((lineOfData = sr.ReadLine()) != null)
{
result += lineOfData;
}
}
}
}
}
catch (IsolatedStorageException)
{
result = string.Empty; // may have partial data/file before error
}
return result;

You can use
StreamReader.Writeline
and
StreamRead.ReadLine
to write and read blocks of text seperated by line feeds.

Related

C# Azure.Storage.Blobs SDK How to list and zip all files in a container and store the zip in another container

I have around 100 files in a container . I want to call a function to zip all files and send it to another container . I am using the Azure.Storage.Blobs version 12.9.1
var blob = container.GetBlockBlobReference(outputFilename);
using (var stream = await blob.OpenWriteAsync())
using (var zip = new ZipArchive(stream, ZipArchiveMode.Create))
{
for (int i = 0; i < 2000; i++)
{
using (var randomStream = CreateRandomStream(2))
{
var entry = zip.CreateEntry($"{i}.zip", CompressionLevel.Optimal);
using (var innerFile = entry.Open())
{
await randomStream.CopyToAsync(innerFile);
}
}
}
}
This is for the older version . How can we achieve it using the new sdk
Can you please try with this code.
Solution 1: Try this code to generate Zip file. After generating zip file upload it to container
public void ZipFilesToResponse(HttpResponseBase response, IEnumerable<Asset> files, string zipFileName)
{
using (var zipOutputStream = new ZipOutputStream(response.OutputStream))
{
zipOutputStream.SetLevel(0); // 0 - store only to 9 - means best compression
response.BufferOutput = false;
response.AddHeader("Content-Disposition", "attachment; filename=" + zipFileName);
response.ContentType = "application/octet-stream";
foreach (var file in files)
{
var entry = new ZipEntry(file.FilenameSlug())
{
DateTime = DateTime.Now,
Size = file.Filesize
};
zipOutputStream.PutNextEntry(entry);
storageService.ReadToStream(file, zipOutputStream);
response.Flush();
if (!response.IsClientConnected)
{
break;
}
}
zipOutputStream.Finish();
zipOutputStream.Close();
}
response.End();
}
For more details refer this link
Solution 2:Also try with this code
using System;
using System.Threading.Tasks;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
namespace SO68566758
{
class Program
{
private const string connectionString = "DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key";
private const string sourceContainer = "source-container";
private const string targetContainer = "target-container";
private const string outputBlobName = "backup.zip";
static async Task Main(string[] args)
{
BlobServiceClient serviceClient = new BlobServiceClient(connectionString);
BlobContainerClient sourceContainerClient = serviceClient.GetBlobContainerClient(sourceContainer);
BlobContainerClient targetContainerClient = serviceClient.GetBlobContainerClient(targetContainer);
var blobs = sourceContainerClient.GetBlobsAsync();
using (var fs = new FileStream(outputBlobName, FileMode.OpenOrCreate))
{
using (var zipOutputStream = new ZipOutputStream(fs))
{
await foreach (var blob in blobs)
{
var blobName = blob.Name;
var blobClient = sourceContainerClient.GetBlobClient(blobName);
//var downloadResponse = await blobClient.DownloadAsync();
//var streamContent = downloadResponse.Value.Content;
var entry = new ZipEntry(blobName);
zipOutputStream.PutNextEntry(entry);
await blobClient.DownloadToAsync(zipOutputStream);
}
}
}
BlobClient targetBlob = targetContainerClient.GetBlobClient(outputBlobName);
using (FileStream fs = new FileStream(outputBlobName, FileMode.Open))
{
await targetBlob.UploadAsync(fs);
}
}
}
}

Combining forms while retaining form fonts in itext7

I am trying to fill and combine multiple forms without flattening(need to keep them interactive for users). However I notice a problem. I have PDF files that contain the forms I am trying to fill. The form fields have their fonts set in adobe PDF. I notice after I combine the forms the fields lose their original fonts. Here is my program.
using iText.Forms;
using iText.Kernel.Pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace PdfCombineTest
{
class Program
{
static void Main(string[] args)
{
Stream file1;
Stream file2;
using (var stream = new FileStream("./pdf-form-1.pdf", FileMode.Open, FileAccess.Read))
{
file1 = Program.Fill(stream, new[] { KeyValuePair.Create("Text1", "TESTING"), KeyValuePair.Create("CheckBox1", "Yes") });
}
using (var stream = new FileStream("./pdf-form-2.pdf", FileMode.Open, FileAccess.Read))
{
file2 = Program.Fill(stream, new[] { KeyValuePair.Create("Text2", "text 2 text") });
}
using (Stream output = Program.Combine(new[] { file1, file2 }))
{
using (var fileStream = File.Create("./output.pdf"))
{
output.CopyTo(fileStream);
}
}
}
public static Stream Combine(params Stream[] streams)
{
MemoryStream copyStream = new MemoryStream();
PdfWriter writer = new PdfWriter(copyStream);
writer.SetSmartMode(true);
writer.SetCloseStream(false);
PdfPageFormCopier formCopier = new PdfPageFormCopier();
using (PdfDocument combined = new PdfDocument(writer))
{
combined.InitializeOutlines();
foreach (var stream in streams)
{
using (PdfDocument document = new PdfDocument(new PdfReader(stream)))
{
document.CopyPagesTo(1, document.GetNumberOfPages(), combined, formCopier);
}
}
}
copyStream.Seek(0, SeekOrigin.Begin);
return copyStream;
}
public static Stream Fill(Stream inputStream, IEnumerable<KeyValuePair<string, string>> keyValuePairs)
{
MemoryStream outputStream = new MemoryStream();
PdfWriter writer = new PdfWriter(outputStream);
writer.SetCloseStream(false);
using (PdfDocument document = new PdfDocument(new PdfReader(inputStream), writer))
{
PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(document, true);
acroForm.SetGenerateAppearance(true);
IDictionary<string, iText.Forms.Fields.PdfFormField> fields = acroForm.GetFormFields();
foreach (var kvp in keyValuePairs)
{
fields[kvp.Key].SetValue(kvp.Value);
}
}
outputStream.Seek(0, SeekOrigin.Begin);
return outputStream;
}
}
}
I've noticed after several hours of debugging that PdfPageFormCopier excludes the default resources which contain fonts when merging form fields, is there a way around this? The project I'm working on currently does this process in ItextSharp and it works as intended. However we are looking to migrate to iText7.
Here are links to some sample pdf's I made I can't upload the actual pdf's I'm working with but these display the same problem.
https://www.dropbox.com/s/pukt91d4xe8gmmo/pdf-form-1.pdf?dl=0
https://www.dropbox.com/s/c52x6bc99gnrvo6/pdf-form-2.pdf?dl=0
So my solution was to modify the PdfPageFormCopier class from iText. The main issue is in the function below.
public virtual void Copy(PdfPage fromPage, PdfPage toPage) {
if (documentFrom != fromPage.GetDocument()) {
documentFrom = fromPage.GetDocument();
formFrom = PdfAcroForm.GetAcroForm(documentFrom, false);
}
if (documentTo != toPage.GetDocument()) {
documentTo = toPage.GetDocument();
formTo = PdfAcroForm.GetAcroForm(documentTo, true);
}
if (formFrom == null) {
return;
}
//duplicate AcroForm dictionary
IList<PdfName> excludedKeys = new List<PdfName>();
excludedKeys.Add(PdfName.Fields);
excludedKeys.Add(PdfName.DR);
PdfDictionary dict = formFrom.GetPdfObject().CopyTo(documentTo, excludedKeys, false);
formTo.GetPdfObject().MergeDifferent(dict);
IDictionary<String, PdfFormField> fieldsFrom = formFrom.GetFormFields();
if (fieldsFrom.Count <= 0) {
return;
}
IDictionary<String, PdfFormField> fieldsTo = formTo.GetFormFields();
IList<PdfAnnotation> annots = toPage.GetAnnotations();
foreach (PdfAnnotation annot in annots) {
if (!annot.GetSubtype().Equals(PdfName.Widget)) {
continue;
}
CopyField(toPage, fieldsFrom, fieldsTo, annot);
}
}
Specifically the line here.
excludedKeys.Add(PdfName.DR);
If you walk the the code in the CopyField() function eventually you will end in the PdfFormField class. You can see the constructor below.
public PdfFormField(PdfDictionary pdfObject)
: base(pdfObject) {
EnsureObjectIsAddedToDocument(pdfObject);
SetForbidRelease();
RetrieveStyles();
}
The function RetrieveStyles() will try to set the font for the field based on the default appearance. However that will not work. Due to the function below.
private PdfFont ResolveFontName(String fontName) {
PdfDictionary defaultResources = (PdfDictionary)GetAcroFormObject(PdfName.DR, PdfObject.DICTIONARY);
PdfDictionary defaultFontDic = defaultResources != null ? defaultResources.GetAsDictionary(PdfName.Font) :
null;
if (fontName != null && defaultFontDic != null) {
PdfDictionary daFontDict = defaultFontDic.GetAsDictionary(new PdfName(fontName));
if (daFontDict != null) {
return GetDocument().GetFont(daFontDict);
}
}
return null;
}
You see it is trying to see if the font exists in the default resources which was explicitly excluded in the PdfPageFormCopier class. It will never find the font.
So my solution was to create my own class that implements the IPdfPageExtraCopier interface. I copied the code from the PdfPageFormCopier class and removed the one line excluding the default resources. Then I use my own copier class in my code. Not the prettiest solution but it works.

IMB barcode could not be read

I have tried to read IMB barcode from an image with the below code snippet, but it always return null. I have also tried with the IMB barcode images in the blackbox testing below, but doesn't work.
https://github.com/micjahn/ZXing.Net/tree/master/Source/test/data/blackbox/imb-1
private static void Decode()
{
Bitmap bitmap = new Bitmap(#"\07.png");
try
{
MemoryStream memoryStream = new MemoryStream();
bitmap.Save(memoryStream, ImageFormat.Bmp);
byte[] byteArray = memoryStream.GetBuffer();
ZXing.LuminanceSource source = new RGBLuminanceSource(byteArray, bitmap.Width, bitmap.Height);
var binarizer = new HybridBinarizer(source);
var binBitmap = new BinaryBitmap(binarizer);
IMBReader imbReader = new IMBReader();
Result str = imbReader.decode(binBitmap);
}
catch { }
}
I have solved this problem by using the below code snippet shared through the below link.
https://github.com/micjahn/ZXing.Net/issues/59
private static void Decode2()
{
var bitmap = new Bitmap(#"\07.png"); // make sure that the file exists at the root level
try
{
var imbReader = new BarcodeReader
{
Options =
{
PossibleFormats = new List<BarcodeFormat> {BarcodeFormat.IMB}
}
};
var result = imbReader.Decode(bitmap);
if (result != null)
System.Console.WriteLine(result.Text);
else
System.Console.WriteLine("nothing found");
}
catch (System.Exception exc)
{
System.Console.WriteLine(exc.ToString());
}
}

MVC 6 HttpPostedFileBase?

I am attempting to upload an image using MVC 6; however, I am not able to find the class HttpPostedFileBase. I have checked the GitHub and did not have any luck. Does anyone know the correct way to upload a file in MVC6?
MVC 6 used another mechanism to upload files. You can get more examples on GitHub or other sources. Just use IFormFile as a parameter of your action or a collection of files or IFormFileCollection if you want upload few files in the same time:
public async Task<IActionResult> UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
var fileName = parsedContentDisposition.FileName;
}
...
}
[HttpPost]
public async Task<IActionResult> UploadMultiple(ICollection<IFormFile> files)
{
var uploads = Path.Combine(_environment.WebRootPath,"uploads");
foreach(var file in files)
{
if(file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
await file.SaveAsAsync(Path.Combine(uploads,fileName));
}
...
}
}
You can see current contract of IFormFile in asp.net sources. See also ContentDispositionHeaderValue for additional file info.
There is no HttpPostedFileBase in MVC6. You can use IFormFile instead.
Example: https://github.com/aspnet/Mvc/blob/dev/test/WebSites/ModelBindingWebSite/Controllers/FileUploadController.cs
Snippet from the above link:
public FileDetails UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
fileDetails = new FileDetails
{
Filename = parsedContentDisposition.FileName,
Content = fileContent
};
}
return fileDetails;
}
I was searching around for quite a while trying to piece this together in .net core and ended up with the below. The Base64 conversion will be next to be done so that the retrieval and display is a little easier. I have used IFormFileCollection to be able to do multiple files.
[HttpPost]
public async Task<IActionResult> Create(IFormFileCollection files)
{
Models.File fileIn = new Models.File();
if(model != null && files != null)
{
foreach (var file in files)
{
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
byte[] fileBytes = null;
using (var fileStream = file.OpenReadStream())
using (var ms = new MemoryStream())
{
fileStream.CopyTo(ms);
fileBytes = ms.ToArray();
//string s = Convert.ToBase64String(fileBytes);
// act on the Base64 data
}
fileIn.Filename = fileName;
fileIn.FileLength = Convert.ToInt32(file.Length);
fileIn.FileType = file.ContentType;
fileIn.FileTypeId = model.FileTypeId;
fileIn.FileData = fileBytes;
_context.Add(fileIn);
await _context.SaveChangesAsync();
}
}
}
return View();
}
EDIT
And below is return of files to a list and then download.
public JsonResult GetAllFiles()
{
var files = _context.File
.Include(a => a.FileCategory)
.Select(a => new
{
id = a.Id.ToString(),
fileName = a.Filename,
fileData = a.FileData,
fileType = a.FileType,
friendlyName = a.FriendlyName,
fileCategory = a.FileCategory.Name.ToLower()
}).ToList();
return Json(files);
}
public FileStreamResult DownloadFileById(int id)
{
// Fetching file encoded code from database.
var file = _context.File.SingleOrDefault(f => f.Id == id);
var fileData = file.FileData;
var fileName = file.Filename;
// Converting to code to byte array
byte[] bytes = Convert.FromBase64String(fileData);
// Converting byte array to memory stream.
MemoryStream stream = new MemoryStream(bytes);
// Create final file stream result.
FileStreamResult fileStream = new FileStreamResult(stream, "*/*");
// File name with file extension.
fileStream.FileDownloadName = fileName;
return fileStream;
}

How to upload images to facebook which is selected by using photoChooserTask in windows phone 8?

I am developing a Windows Phone app in which I have to post a photo to facebook. And that particular photo is choosen by using PhotoChooserTask or CameraChooserTask.
Normally, I can post a particular photo successfully, but I am facing problem to post the selected photo. I saw some link like
link
So please if anyone know about the issue please help me out.
Thanx in advance.
EDIT
private void PostClicked(object sender, RoutedEventArgs e)
{
//Client Parameters
var parameters = new Dictionary<string, object>();
//var parameters1 = new Dictionary<>();
parameters["client_id"] = FBApi;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
parameters["ContentType"] = "image/png";
//The scope is what give us the access to the users data, in this case
//we just want to publish on his wall
parameters["scope"] = "publish_stream";
Browser.Visibility = System.Windows.Visibility.Visible;
Browser.Navigate(client.GetLoginUrl(parameters));
}
private void BrowserNavitaged(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
//Making sure that the url actually has the access token
if (!client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
//Checking that the user successfully accepted our app, otherwise just show the error
if (oauthResult.IsSuccess)
{
//Process result
client.AccessToken = oauthResult.AccessToken;
//Hide the browser
Browser.Visibility = System.Windows.Visibility.Collapsed;
PostToWall();
}
else
{
//Process Error
MessageBox.Show(oauthResult.ErrorDescription);
Browser.Visibility = System.Windows.Visibility.Collapsed;
}
}
private void PostToWall()
{
string imageName = "ic_launcher.png";
StreamResourceInfo sri = null;
Uri jpegUri = new Uri(imageName, UriKind.Relative);
sri = Application.GetResourceStream(jpegUri);
try
{
byte[] imageData = new byte[sri.Stream.Length];
sri.Stream.Read(imageData, 0, System.Convert.ToInt32(sri.Stream.Length));
FacebookMediaObject fbUpload = new FacebookMediaObject
{
FileName = imageName,
ContentType = "image/jpg"
};
fbUpload.SetValue(imageData);
string name1 = eventname.Text;
string format = "yyyy-MM-dd";
string message1 = eventmessage.Text;
string date1 = datepicker.ValueString;
DateTime datevalue = DateTime.Parse(date1);
string d = datevalue.ToString(format);
string memoType = "Tribute";
var parameters = new Dictionary<string, object>();
var parameters1 = new Dictionary<string, object>();
parameters["message"] = name1 + "\n" + d + "\n" + memoType + "\n" + message1;
parameters["source"] = fbUpload;
webservice();
client.PostTaskAsync("me/photos", parameters);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
//client.PostTaskAsync("me/photos", parameters1);
}
On clicking on a button I am calling PostClicked class and it will directly go to facebook mainpage and it will ask for login information. Like this I am doing.
Please check it out
Now I can share a photo to facebook successfully by using photochoosertask or cameratask.
I am sharing my experience so that if anyone face the same issue can use it.
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
BitmapImage image = new BitmapImage();
image.SetSource(e.ChosenPhoto);
SaveImageToIsolatedStorage(image, tempJPEG);
this.image.Source = image;
}
public void SaveImageToIsolatedStorage(BitmapImage image, string fileName)
{
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(fileName))
isolatedStorage.DeleteFile(fileName);
var fileStream = isolatedStorage.CreateFile(fileName);
if (image != null)
{
var wb = new WriteableBitmap(image);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
}
fileStream.Close();
}
}
With this you can able to save the selected image to IsolatedStorage.
And then at the time of posting the photo to facebook you have to select the image from IsolatedStorage.
private void PostClicked(object sender, RoutedEventArgs e)
{
//Client Parameters
var parameters = new Dictionary<string, object>();
parameters["client_id"] = FBApi;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
//The scope is what give us the access to the users data, in this case
//we just want to publish on his wall
parameters["scope"] = "publish_stream";
Browser.Visibility = System.Windows.Visibility.Visible;
Browser.Navigate(client.GetLoginUrl(parameters));
}
private void BrowserNavitaged(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
//Making sure that the url actually has the access token
if (!client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
//Checking that the user successfully accepted our app, otherwise just show the error
if (oauthResult.IsSuccess)
{
//Process result
client.AccessToken = oauthResult.AccessToken;
//Hide the browser
Browser.Visibility = System.Windows.Visibility.Collapsed;
PostToWall();
}
else
{
//Process Error
MessageBox.Show(oauthResult.ErrorDescription);
Browser.Visibility = System.Windows.Visibility.Collapsed;
}
}
private void PostToWall()
{
try
{
byte[] data;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read))
{
data = new byte[fileStream.Length];
fileStream.Read(data, 0, data.Length);
fileStream.Close();
}
}
//MemoryStream ms = new MemoryStream(data);
//BitmapImage bi = new BitmapImage();
//// Set bitmap source to memory stream
//bi.SetSource(ms);
//this.imageTribute.Source = bi;
FacebookMediaObject fbUpload = new FacebookMediaObject
{
FileName = tempJPEG,
ContentType = "image/jpg"
};
fbUpload.SetValue(data);
string name1 = eventname.Text;
string format = "yyyy-MM-dd";
string message1 = eventmessage.Text;
string date1 = datepicker.ValueString;
DateTime datevalue = DateTime.Parse(date1);
string d = datevalue.ToString(format);
string memoType = "Notice";
var parameters = new Dictionary<string, object>();
var parameters1 = new Dictionary<string, object>();
parameters["message"] = name1;
parameters["source"] = fbUpload;
webservice();
client.PostTaskAsync("me/photos", parameters);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
Thanx to all....
you can do that by two methods :
1) by using mediasharetask in which it will show u all sharing account to which your phone is synced like facebook,gmail,linkdin,twitter,etc : it can be used like like this.
ShareMediaTask shareMediaTask = new ShareMediaTask();
shareMediaTask.FilePath = path;
shareMediaTask.Show();
2) by using facebook sdk. you can get the package from nuget manager and then u can use it to share on facebook.
I hope this might help u.

Resources