Importing content to XNA program using code? - xna

Is it possible that a XNA program able to import the resource (etc: image, sound) into the content of the program via code? For example, the user want to add an new image into the program, the XNA program will behave like the Window's Add File or Copy File. If possible WinForm shall avoid.

OpenFileDialog f = new OpenFileDialog();
f.Filter = "PNG files (*.png)|*.png|All files (*.*)|*.*";
f.Title = "Import Image";
DialogResult result = f.ShowDialog(); // Show the dialog.
string file = "";
if (result == DialogResult.OK) // Test result.
{
file = f.FileName;
}
else //If cancels, handle here
Application.Exit();
using (FileStream SourceStream = File.Open(file, FileMode.Open))
{
//Load the Texture here
YourTexture = Texture2D.FromStream(GraphicsDevice, SourceStream);
}
That uses a simple WinForms OpenDialog Window, but if you don't want winforms, you can make your own and use this part just to load.
using (FileStream SourceStream = File.Open(file, FileMode.Open))
{
//Load the Texture here
YourTexture = Texture2D.FromStream(GraphicsDevice, SourceStream);
}
You can save the Texture2D Back by doing
using(Stream stream = File.Create(file));
{
texture.SaveAsPng(stream, texture.Width, texture.Height);
}

Related

can eml directly open with outlook, instead eml file will download then click it to open in outlook?

I have an asp.net MVC application, below code works file.
But the code is that, When navigate to Email action in browser, an EML file is download, then when we click on that file, the file will open with outlook.
Can it be possible, when action calls, then EML file will directly open with outlook, instead of download and then click to open??
Code
public async Task<FileStreamResult> Email()
{
string dummyEmail = "test#localhost.com";
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(dummyEmail);
mailMessage.To.Add("dejan.caric#gmail.com");
mailMessage.Subject = "Test subject";
mailMessage.Body = "Test body";
// mark as draft
mailMessage.Headers.Add("X-Unsent", "1");
// download image and save it as attachment
using (var httpClient = new HttpClient())
{
var imageStream = await httpClient.GetStreamAsync(new Uri("http://dcaric.com/favicon.ico"));
mailMessage.Attachments.Add(new Attachment(imageStream, "favicon.ico"));
}
var stream = new MemoryStream();
ToEmlStream(mailMessage, stream, dummyEmail);
stream.Position = 0;
return File(stream, "message/rfc822", "test_email.eml");
}
private void ToEmlStream(MailMessage msg, Stream str, string dummyEmail)
{
using (var client = new SmtpClient())
{
var id = Guid.NewGuid();
var tempFolder = Path.Combine(Path.GetTempPath(), Assembly.GetExecutingAssembly().GetName().Name);
tempFolder = Path.Combine(tempFolder, "MailMessageToEMLTemp");
// create a temp folder to hold just this .eml file so that we can find it easily.
tempFolder = Path.Combine(tempFolder, id.ToString());
if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
}
client.UseDefaultCredentials = true;
client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.PickupDirectoryLocation = tempFolder;
client.Send(msg);
// tempFolder should contain 1 eml file
var filePath = Directory.GetFiles(tempFolder).Single();
// create new file and remove all lines that start with 'X-Sender:' or 'From:'
string newFile = Path.Combine(tempFolder, "modified.eml");
using (var sr = new StreamReader(filePath))
{
using (var sw = new StreamWriter(newFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (!line.StartsWith("X-Sender:") &&
!line.StartsWith("From:") &&
// dummy email which is used if receiver address is empty
!line.StartsWith("X-Receiver: " + dummyEmail) &&
// dummy email which is used if receiver address is empty
!line.StartsWith("To: " + dummyEmail))
{
sw.WriteLine(line);
}
}
}
}
// stream out the contents
using (var fs = new FileStream(newFile, FileMode.Open))
{
fs.CopyTo(str);
}
}
}
With Chrome you can make it automatically open certain files, once they are downloaded.
.EML should attempt to open in Outlook.
I am not sure about other browsers, but Chrome seemed to be the only one with this option.
It's not a pefect solution because if someone downloaded an .EML from another website in Chrome, it will open automatically aswell.
I recommend having Chrome dedicated to your Web application.
You sure can open local .eml file with Outlook.
But in context of web application, you must firstly download it.

Converting PDF with form to PDF without form

i have a PDF template containing a form. At present, I'm using itextpdf to fill the form fields, and save the resulting pdf.
Is there a way to get completeley rid of the pdf form (i.e. converting the pdf to a form-free pdf containing the inserted data)?
You need to set setFormFlattening to true on your PdfStamper object.
Code is from their documentation:
for (Movie movie : PojoFactory.getMovies(connection)) {
if (count == 0) {
baos = new ByteArrayOutputStream();
reader = new PdfReader(RESOURCE);
stamper = new PdfStamper(reader, baos);
stamper.setFormFlattening(true);
form = stamper.getAcroFields();
}
count++;
}
if (count > 0) {
stamper.close();
reader = new PdfReader(baos.toByteArray());
copy.addPage(copy.getImportedPage(reader, 1));
}
That way the form will be flattened when you close your PdfStamper.

Cordova Phonegap inappbrowser losing File Api functionality

I am developing an app using Web Audio Api. I have discovered that there is a memory leak in the way that Safari handles audio and doesn't garbage college the Audio Context correctly. For this reason I wish to load a new page. Have that page create the Audio Context, complete the operation and then close the window, so that the memory is released.
I have done the following to achieve this.
ref = window.open('record.html', '_self'); This will open the record.html page in the Cordova WebView according to https://wiki.apache.org/cordova/InAppBrowser
1 window.open('local-url.html');// loads in the
Cordova WebView
2 window.open('local-url.html', '_self');
// loads in the Cordova WebView
The record.html page loads a javascript file, that runs the operations that I wish to run. Here is the recordLoad.js file that makes some calls to native operations ( The native API is only available if loaded in the Cordova Webview and as you can see I need to access the file system, so this is the only way I can see to do it.
window.onload = createAudioContext;
ref = null;
function createAudioContext(){
console.log('createAudioContext');
window.AudioContext = window.AudioContext || window.webkitAudioContext;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
window.URL = window.URL || window.webkitURL;
audioContext = new AudioContext;
getDirectory();
}
function getDirectory(){
console.log('getDirectory');
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, getFileSystem, fail);
}
function getFileSystem(directory){
console.log('getFileSystem');
var audioPath = localStorage.getItem('audioPath');
directory.root.getFile(audioPath, null, getVocalFile, fail);
}
function getVocalFile(fileEntry){
console.log('getVocalFile');
fileEntry.file(readVocalsToBuffer, fail);
}
function readVocalsToBuffer(file){
console.log('readVocalsToBuffer');
var reader = new FileReader();
reader.onloadend = function(evt){
var x = audioContext.decodeAudioData(evt.target._result, function(buffer){
if(!buffer){
console.log('error decoding file to Audio Buffer');
return;
}
window.voiceBuffer = buffer;
buffer = null;
loadBuffers();
});
}
reader.readAsArrayBuffer(file);
}
//web
function loadBuffers(){
console.log('loadBuffers');
var srcSong = localStorage.getItem('srcSong');
try{
var bufferLoader = new BufferLoader(
audioContext,
[
"."+srcSong
],
createOffLineContext
);
bufferLoader.load()
}
catch(e){
console.log(e.message);
}
}
//
function createOffLineContext(bufferList){
console.log('createOfflineContext');
offline = new webkitOfflineAudioContext(2, window.voiceBuffer.length, 44100);
var vocalSource = offline.createBufferSource();
vocalSource.buffer = window.voiceBuffer;
vocalSource.connect(offline.destination);
var backing = offline.createBufferSource();
backing.buffer = bufferList[0];
backing.connect(offline.destination);
vocalSource.start(0);
backing.start(0);
offline.oncomplete = function(ev){
bufferList = null;
console.log('audioContext');
console.log(audioContext);
audioContext = null;
console.log(audioContext);
vocalSource.stop(0);
backing.stop(0);
vocalSource.disconnect(0);
backing.disconnect(0);
vocalSource = null;
backing = null;
window.voiceBuffer = null;
window.renderedFile = ev.renderedBuffer;
var bufferR = ev.renderedBuffer.getChannelData(0);
var bufferL = ev.renderedBuffer.getChannelData(1);
var interleaved = interleave(bufferL, bufferR);
var dataview = encodeWAV(interleaved);
window.audioBlob = new Blob([dataview], {type: 'Wav'});
saveFile();
}
offline.startRendering();
}
// This file is very long, but once it is finished mixing the two audio buffers it writes a new file to the file system. And when that operation is complete I use
function gotFileWriter(writer){
console.log('gotFileWriter');
writer.onwriteend = function(evt){
console.log('onwriteEnd');
console.log(window.audioBlob);
delete window.audioBlob;
console.log(window.audioBlob);
// checkDirectory();
var ref = window.open('index.html', '_self');
// ref.addEventListener('exit', windowClose);
}
writer.write(audioBlob);
}
I return back to the original index.html file. This solves the memory issues. However, once I try to run the same operation a second time. ie load in the record.html file, and run the recordLoad.js file I receive an error ReferenceError: Can't find variable: LocalFileSystem
It would appear that in reload index.html some, but not all of the links to the Cordova API have been lost. I can still for example use the Media Api but not the File Api. I understand that this is a bit of a hacky way, (opening and closing windows) to solve the memory leak, but I cannot find any other way of doing it. I really need some help with this. So any pointers very very welcome.

XNA XBOX highscore port

I'm trying to port my pc XNA game to the xbox and have tried to implement xna easystorage alongside my existing pc file management for highscores. Basically trying to combine http://xnaessentials.com/tutorials/highscores.aspx/tutorials/highscores.aspx with http://easystorage.codeplex.com/
I'm running into one specific error regarding the LoadHighScores() as error with 'return (data);' - Use of unassigned local variable 'data'.
I presume this is due to async design of easystorage/xbox!? but not sure how to resolve - below are code samples:
ORIGINAL PC CODE: (works on PC)
public static HighScoreData LoadHighScores(string filename)
{
HighScoreData data; // Get the path of the save game
string fullpath = "Content/highscores.lst";
// Open the file
FileStream stream = File.Open(fullpath, FileMode.Open,FileAccess.Read);
try
{ // Read the data from the file
XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
data = (HighScoreData)serializer.Deserialize(stream);
}
finally
{ // Close the file
stream.Close();
}
return (data);
}
XBOX PORT: (with error)
public static HighScoreData LoadHighScores(string container, string filename)
{
HighScoreData data;
if (Global.SaveDevice.FileExists(container, filename))
{
Global.SaveDevice.Load(container, filename, stream =>
{
File.Open(Global.fileName_options, FileMode.Open,//FileMode.OpenOrCreate,
FileAccess.Read);
try
{
// Read the data from the file
XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
data = (HighScoreData)serializer.Deserialize(stream);
}
finally
{
// Close the file
stream.Close();
}
});
}
return (data);
}
Any ideas?
Assign data before return. ;)
data = (if_struct) ? new your_struct() : null;
if (Global.SaveDevice.FileExists(container, filename))
{
......
}
return (data);
}

Extracting jfif image from 2d barcode

I have data read from 2d bar code pdf417. It contains an embedded image in the format of (jfif), The image is not at the beginning of the decoded data it has some data fields and the image is somewhere after, the data fields does not seam to have fixed lengths. How can I extract the Image from the decoded data. I used ClearImage Library to decode the barcode and I have it as text and Hex.
Please help. Thank you in advance
I was able to extract the image thanks to many experts in StackOverflow, I have being reviewing their posts. The following code explains how to extract the image from a mixed binary file, the code is not so beautiful but it can do the job. It searches for (JFIF) image header and extracts it into an image file.
public static void ExtractImage(string fname)
{
try
{
FileStream fs = new FileStream(fname, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
//read the first binary
char[] soi="Empty".ToCharArray();
br.BaseStream.Position = 0;
long imgpos = 0;
ushort r = 0;
while ((r = br.ReadUInt16())> 0)
{
Console.WriteLine(r);
if (r == 0xd8ff)
{
Console.WriteLine("Detcted----->");
imgpos = br.BaseStream.Position;
break;
//UInt16 jfif = br.ReadUInt16(); // JFIF marker
//Console.WriteLine("jfif " + jfif);
//if (jfif == 0xe0ff || jfif == 57855)
// Console.WriteLine(" also Detected--->");
}
}
//now copy to stream
FileStream str = new FileStream("bcimage.jpg", FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(str);
br.BaseStream.Position = imgpos-2;
int l = (int)(fs.Length - imgpos - 2);
bw.Write(br.ReadBytes(l));
fs.Close();
br.Close();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}

Resources